2

I am using following code and could you please let me know how to construct the nested json.

   public String getJsonString() {

        String str = null;
        JSONGenerator gen = JSON.createGenerator(true);
        gen.writeStartArray();
        gen.writeStartObject();
        gen.writeStringField('title', 'ParentNode');
        gen.writeStringField('key', 'I1');
        gen.writeBooleanField('isFolder',true);
        integer i;
                      for(i = 0;i<10;i++){
                           gen.writeFieldName('children');
                            gen.writeStartArray();
                            gen.writeStartObject();
                            gen.writeStringField('title', i+'node');
                            gen.writeBooleanField('isFolder',true);
                            gen.writeEndObject();
                            gen.writeEndArray();
                        }

        gen.writeEndObject();
        gen.writeEndArray();
        str = gen.getAsString();
        return str; 
    }

Above the code output is:

enter image description here

1

TRY THIS

for(i = 0;i<10;i++){

                           gen.writeFieldName('children');
                            gen.writeStartArray();
                            gen.writeStartObject();
                            gen.writeStringField('title', i+'node');
                            gen.writeBooleanField('isFolder',true);


                        }
                         for(i = 0;i<10;i++){
                             gen.writeEndObject();
                            gen.writeEndArray();
                            }
6

The JSONGenerator class requires you the programmer to make quite fine grained calls to create the JSON and it is easy to get those wrong.

If the JSON objects have fixed fields, using the below approach instead avoids that problem and provides Apex classes that can be passed around in your code and that JSON can be deserialized into:

public class Parent {
    public String title;
    public String key;
    public Boolean isFolder;
    public Child[] children = new Child[] {};
}

public class Child {
    public String title;
    public Boolean isFolder;
}

public String getJsonString() {
    Parent p = new Parent();
    p.title = 'ParentNode';
    p.key = 'I1';
    p.isFolder = true;
    for(Integer i = 0; i < 10; i++) {
        Child c = new Child();
        c.title = i + 'node';
        c.isFolder = true;
        p.children.add(c);
    }
    return JSON.serializePretty(p);
}
  • can you answer for this salesforce.stackexchange.com/questions/37346/how-to-make-the-context-menu-for-the-below-code – Alex May 31 '14 at 11:43

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.