Hi ,
Here we are going to learn how to generate JSON with the help of Map in apex.
Let's take the following JSON and see how to generate the same with the help of Map in apex.
JSON:
{
"lastname":"SF",
"firstname":"Techbook",
"account":{
"name":"Salesforce Techbook",
"address":{
"shippingstreet":"test_street",
"shippingcity":"test_city"
}
},
"phone":"12454565",
"mailingcity":"test_cont_City"
}
Let's try to generate the above JSON with Map:
//Preparation of outer JSON object
Map<String,Object> jsonGenMap = new Map<String,Object>();
jsonGenMap.put('lastname','SF');
jsonGenMap.put('firstname','Techbook');
jsonGenMap.put('phone','12454565');
jsonGenMap.put('mailingcity','test_cont_City');
//Preparation of "account" JSON object
Map<String,Object> jsonActMap = new Map<String,Object>();
jsonActMap.put('name','Salesforce Techbook');
Map<String,Object> jsonActAddressMap = new Map<String,Object>();
jsonActAddressMap.put('shippingstreet','test_street');
jsonActAddressMap.put('shippingcity','test_city');
jsonActMap.put('address',jsonActAddressMap);
jsonGenMap.put('account',jsonActMap);
//Generation of JSON from the above with the help of "serialize" method under "JSON" class.
string jsonstring = JSON.serialize(jsonGenMap);
System.debug(jsonstring);
References:
https://developer.salesforce.com/docs/atlas.en-us.apexref.meta/apexref/apex_class_System_Json.htm
No comments:
Post a Comment