I am using code like below

global with sharing class ClassA 
    global static void createSomething(Wrapper1 req)
        System.debug('###stringVar1 :' + req.stringVar1);
        System.debug('###stringVar2:' + req.stringVar2);
        System.debug('###Wrapper2:' + req.Wrapper2);

        Object__c obj = new Object__c();
        obj.fld1 = req.stringVar1;
        obj.fld2 = req.stringVar2;
        insert obj;

        List<Object2__c> surveyQuestionsRespList = new List<Object2__c>();
        for(Wrapper2 question : req.Wrapper2)
            Object2__c obj2 = new Object2__c();
            obj2.fld4 = question.response;
            obj2.fld3 = question.someId;
            obj2.Object__c = obj.Id;
        insert surveyQuestionsRespList;                

    global with sharing class Wrapper1
        public String stringVar1{get;set;}
        public String stringVar2{get;set;}
        public List<Wrapper2> Wrapper2{get;set;}        

    global with sharing class Wrapper2
        public String someId{get;set;}
        public String response{get;set;}

How can I generate JSON for this class. Please help me. Thanks in advance.

  • what is the issue here can you please explain ? if you json is like Wrapper1 structure then it should work I guess.. – Ratan Paul Apr 15 '16 at 5:00
  • 1
    Have you checked json2apex.herokuapp.com ? – Boris Bachovski Apr 15 '16 at 5:01
  • thanks for reply, I want provide JSON using this class. But I don't know how to use serialize method for this class for generating JSON. – Venkata Raja Apr 15 '16 at 5:06
  • I want allow others to send data in JSON format. – Venkata Raja Apr 15 '16 at 5:12

You don't need to do anything "special"; just read the classes from front to back, and write the JSON as you go:

{ "stringVar1": "Value1",
  "stringVar2": "Value2",
  "Wrapper2": [
     { "someId": "Value3",
       "response": "Value4"

You can confirm that you wrote the correct JSON by using json2apex; it should match your original class definitions almost exactly:

public class JSON2Apex {

    public String stringVar1;
    public String stringVar2;
    public List<Wrapper2> Wrapper2;

    public class Wrapper2 {
        public String someId;
        public String response;
| improve this answer | |
  • Thank You! It is helpful. exact JSON for above class:{ "Wrapper2": [ { "someId": "Value3", "response": "Value4", "wrapper3":[ { "someId2": "Value5", "response3": "Value6" } ] } ] } – Venkata Raja Apr 15 '16 at 5:54

Refer to Getting Started with Apex JSON

You can try to initiate your objects and serialise them:

public static void serialiseTest() {
    Wrapper1 w1 = new Wrapper1();
    w1.Wrapper2 = new list<Wrapper2> {new Wrapper2()};
    system.debug( JSON.serialize(w1));


| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.