Create JSON using apex

  • 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.

    Json.serialize(class object) is about all it requires. Lots of already answered questions related to this already here

    There are many simple examples available through a simple web search. Which one are you having trouble with?

  • 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));
    

License under CC-BY-SA with attribution


Content dated before 7/24/2021 11:53 AM