[SalesForce] Serialize a Map into a specific JSON object

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?

Best Answer

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);