0

Hi I need to create a json object iteratively inside a for loop on a keyset of a map: Below my code:

List<String> ts= new List<String>(); 
JSONGenerator gen = JSON.createGenerator(true);
        Set<String> k=mapTypeSubType.keySet();
         gen.writeStartObject();
        for(String key:k){
            if(key !='' && key !=null ){
                System.debug(i);
                i++;
                System.debug('key ' +key);
                System.debug(mapTypeSubType.get(key));
                gen.writeStringField('type',key);
                gen.writeObjectField('subtypes', mapTypeSubType.get(key));
                gen.writeEndObject();
                String pretty = gen.getAsString();
                ts.add(pretty);
            }    
        }

the for loop did one cycle and throw the error "Can not write a field name, expecting a value". How can I do a List of String while I build iteratively a JSON?

  • 1
    Can't you use JSON.serialize method instead of the createGenerator parser. Otherwise, can you post a snippet of code which is not working. – Raul Feb 24 '17 at 12:18
  • I post the code that is not working. I can't use JSON serialize because I sent the result to a method that want a specific data structure – L.benedettini Feb 24 '17 at 12:29
  • I can't run the code, post a working copy of it. You would get better support if you do that – Raul Feb 24 '17 at 12:36
  • You're doing writeEndObject() inside your loop. Seems like writeStartObject() should either be moved into the loop, or writeEndObject() should move out of the loop. – Jeremy Nottingham Feb 24 '17 at 13:10
1

As your requirement is to create JSON list you should create the JSON string inside the for loop itself. I tried to modify your code as below. Please check if this is working for you.

List<String> ts= new List<String>();
Set<String> k=mapTypeSubType.keySet();
JSONGenerator gen;
String pretty;
for(String key:k){    
    if(key !='' && key !=null ){
        gen = JSON.createGenerator(true);
        gen.writeStartObject();        
        gen.writeStringField('type',key);
        gen.writeObjectField('subtypes', mapTypeSubType.get(key));
        gen.writeEndObject();
        pretty = gen.getAsString();
        ts.add(pretty);        
    }
}
System.debug('%%% '+ts);

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.