7

I built a Map and serialized it into a JSON object, my code below:

Map<String,List<String>> mapTypeSubType= new Map<String,List<String>>();
if(actionPlanB2C.size()>0){
            for(OCTO_Action_Plan__c pl:actionPlanB2C){
               if(!mapTypeSubType.containskey(pl.OCTO_Type_Label__c)){
                    mapTypeSubType.put(pl.OCTO_Type_Label__c,new List<String> {pl.OCTO_Type_SubLabel__c});
               }else{
                    mapTypeSubType.get(pl.OCTO_Type_Label__c).add(pl.OCTO_Type_SubLabel__c);
               }
            }

        }
System.debug(mapTypeSubType);
String jsonMap=JSON.serialize(mapTypeSubType);
System.debug(jsonMap);

This code create the JSON : {"TEST":["TEST"]}

but I need the JSON object have the form: {"type":"TEST","subtypes":["TEST"]}. How can I serialize a map into a specific JSON object?

12

Here how you can achieve it.

map<string, object> mapToSerialize = new map<string, object>();
mapToSerialize.put('type', 'TEST');
//add you subtype like this
mapToSerialize.put('subtypes', new list<string>{'TEST'});
string jsonstring = JSON.serialize(mapToSerialize);
2

May be the following sample code helps:

Map<Object,List<Object>> mapTypeSubType= new Map<Object,List<Object>>();
for(Integer i=0; i<3; i++){
    if(!mapTypeSubType.containskey('"type":"TEST"')){
        mapTypeSubType.put('"type":"TEST"',new List<Object> {'"subtypes":"TEST"'});
    }else{
        mapTypeSubType.get('"type":"TEST"').add('TEST');
    }
}

System.debug(mapTypeSubType);
String jsonMap=JSON.serialize(mapTypeSubType);
System.debug(jsonMap);

//Here's the debug response:
{"\"type\":\"TEST\"":["\"subtypes\":\"TEST\"","TEST","TEST"]}

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.