• Lessons Home
Topics
Community
  1. Lessons
  2. Integration Fundamentals
  3. Working with JSON
  4. Serializing Apex Objects

      Serializing Apex Objects

      Serializing Apex Objects

      JSON.deserializeUntyped turns JSON text into Apex values. JSON.serialize goes the
      other way: it takes an Apex value and returns the JSON text for it. That is the call
      you need when you build the body of a request.

      A Map Becomes A JSON Object

      Map<String, Object> payload = new Map<String, Object>();
      payload.put('username', username);
      payload.put('password', password);
      String body = JSON.serialize(payload);
      

      The map becomes a JSON object, the keys are the ones you put in, and the values keep
      the type they had. Send the text with request.setBody(body);.

      The Key Order Is Not Yours

      The order of the keys in the text is not the order you put them in. A map filled with
      zebra, alpha and middle comes back as middle, alpha, zebra. Never compare
      serialized text with an expected string, and never build an expected string by hand:
      compare the parsed values instead.

      It Escapes For You

      A value that carries a quote comes back with the quote escaped, and a newline or a
      backslash is escaped too. This is the reason to serialize rather than to join strings
      together: a body built by hand falls apart the moment one value holds a quote.

      The Null Flag Only Covers Apex Objects

      JSON.serialize(value, true) drops the null fields of a class instance. It does not
      touch a map: a null value in a map stays in the text. The flag is named
      suppressApexObjectNulls and it means what it says.

      A Record Brings Its Attributes

      Serializing a record adds an attributes object holding the type and the url of the
      record, plus the Id. When you send data to another service, build a map of the fields
      you want to send instead of serializing the record itself.

      Common Mistakes

      • Building the body by joining strings. One quote in a value and the JSON is broken.
      • Forgetting the Content-Type header. The service cannot read the body and answers
        that the username and password are required.
      • Assuming the keys come out in the order you put them in.
      Apex Code Editor
      Sign in to Submit

      Welcome to Lightning Challenge!

      How It Works

      • • Write your solution in the code editor
      • • Connect your Salesforce org to test
      • • Submit to check if your solution passes
      • • Use hints if you get stuck

      Note

      Complete this lesson challenge to earn points and track your progress. The code editor allows you to implement your solution, and the tests will verify if your code meets the requirements.

      Wally Assistant

      Wally can't hear you

      Please sign in to access the AI Assistant

      Sign In