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?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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);
Method 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"]}
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0