4

I do not have any idea about this, but I am trying to create JSON using Apex class. I think it can be done using serialize method. But I need a simple example so that I can understand the procedure. Any example or easy to understand link would be really appreciated.

2
  • 6
    Json.serialize(class object) is about all it requires. Lots of already answered questions related to this already here
    – Eric
    Oct 8, 2017 at 7:07
  • 1
    There are many simple examples available through a simple web search. Which one are you having trouble with? Oct 8, 2017 at 17:19

2 Answers 2

20

It depends on what you really want to do :

if it's just about serializing an object, the JSON class will be enough by itself.

System.debug(JSON.serialize( [Select Id from Account limit 1] ));

will output something like

[{"attributes":{"type":"Account","url":"/services/data/v40.0/sobjects/Account/0010O00001kzzCtQAI"},"Id":"0010O00001kzzCtQAI"}]

If it's about creating a parameter for an external webservice (or whatever), you might not have a class for the structure you need. Then you can either create a class just for serializing, or simply use a map. Let's say you need a JSON output like :

{
  action : "anAction",
  aLoop : 10,
  ids : [ 10, 12, 15],
  theObject : { objName : "myObj" }
}

You'd have choice between :

create specific classes

class Cl1 {
  public String action;
  public Integer aLoop;
  public List<Integer> ids;
  public Cl2 theObject ;
  public Cl1(String a, Integer l, List<Integer> i, Cl2 o){
    action=a; aLoop=l; ids=i; theObject=o;
  }
}

class Cl2 {
  public String objName;
  public Cl2(String o) {
    objName = o;
  }
}

System.debug( JSON.serialize( new Cl1('anAction', 10, new List<Integer>{10, 12, 15}, new Cl2('myObj'))));

or use a simple map

Map<String, Object> obj = new Map<String, Object>();
obj.put('action', 'anAction');
obj.put('aLoop', 10);
obj.put('ids', new List<Integer>{10, 12, 15});
Map<String, String> theObj = new Map<String, String>();
theObj.put('objName', 'myObj');
obj.put('theObject', theObj);
System.debug(JSON.Serialize(obj));
5

I've never used this myself, but if you need more flexibility than the regular serialize method you can use JSONGenerator. Some sample code taken from the Apex Developer Guide:

public class JSONGeneratorSample{

    public class A { 
        String str;

        public A(String s) { str = s; }
    }

    static void generateJSONContent() {
        // Create a JSONGenerator object.
        // Pass true to the constructor for pretty print formatting.
        JSONGenerator gen = JSON.createGenerator(true);

        // Create a list of integers to write to the JSON string.
        List<integer> intlist = new List<integer>();
        intlist.add(1);
        intlist.add(2);
        intlist.add(3);

        // Create an object to write to the JSON string.
        A x = new A('X');

        // Write data to the JSON string.
        gen.writeStartObject();
        gen.writeNumberField('abc', 1.21);
        gen.writeStringField('def', 'xyz');
        gen.writeFieldName('ghi');
        gen.writeStartObject();

        gen.writeObjectField('aaa', intlist);

        gen.writeEndObject();

        gen.writeFieldName('Object A');

        gen.writeObject(x);

        gen.writeEndObject();

        // Get the JSON string.
        String pretty = gen.getAsString();

        System.assertEquals('{\n' +
        '  "abc" : 1.21,\n' +
        '  "def" : "xyz",\n' +
        '  "ghi" : {\n' +
        '    "aaa" : [ 1, 2, 3 ]\n' +
        '  },\n' +
        '  "Object A" : {\n' +
        '    "str" : "X"\n' +
        '  }\n' +
        '}', pretty);
    }
}

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .