JSON generator not adding comma between objects?

For some strange reason when i try to use the JSON generator to generate some basic JSON using a specific format its not putting a comma between two objects..

here is a simplified example of what im doing

JSONGenerator gen = JSON.createGenerator(true);

gen.writeStartObject();

gen.writeFieldName('folder-1');
gen.writeStartArray();

gen.writeStartObject();
gen.writeStringField('filename', 'fake.jpg');
gen.writeEndObject();

gen.writeEndArray();
gen.writeEndObject();


gen.writeStartObject();

gen.writeFieldName('folder-2');
gen.writeStartArray();

gen.writeStartObject();
gen.writeStringField('filename', 'fake2.jpg');
gen.writeEndObject();

gen.writeEndArray();
gen.writeEndObject();

String pretty = gen.getAsString().replace('\n', '');

return pretty;

and its outputing ALMOST perfectly as

{  "folder-1" : [ {    "filename" : "fake.jpg"  } ]} {  "folder-2" : [ {    "filename" : "fake2.jpg"  } ]}

but you’ll notice there isnt an comma between the two outer objects? i know im close but what im i doing wrong?

Answer

While not a direct answer to your question I wanted to note that it’s often much easier to nest apex data structures and invoke JSON.serialize on that.

Your sample code could be rewritten (including the inclusion of array suggested by other answers) to:

List<Object> rawData = new List<Object>{ //a list of, well, anything really
    new Map<String,Object>{ //first JSON object
        'folder-1' => new List<Object>{
            new Map<String,Object>{
                'filename' => 'fake.jpg'
            }
        }
    },
    new Map<String,Object>{ //second JSON object
        'folder-2' => new List<Object>{
            new Map<String,Object>{
                'filename' => 'fake2.jpg'
            }
        }
    }
};
JSON.serialize(rawData);

This format is, at least to me and those I’ve discussed it with, much easier to visualize when reading the code, and can be constructed dynamically in really any type of structure rather than using the static definition demonstrated here to achieve the same flexibility as the JSONGenerator. The difference is that this is often much easier to work with, and leaves out the risk of unbalanced or invalid JSON being returned.

Attribution
Source : Link , Question Author : Keith Mancuso , Answer Author : ca_peterson

Leave a Comment