Requirement: Convert json Into Apex Wrapper Class
Some times we need to convert json into apex code to perform some operation or to get data available in apex .
So It is quiet simple you need to just use JSON.deserialize method to convert json into wrapper. you can use JSON.deserialize to convert json into any type you want.
Here is the wrapper class to which we convert our json
public class jsonWrapper { public List<List<String>> rows; // here rows is the name of field in json this variable should be taken as the same name youwant to convert field into wrapper fromjson }
// this is json which is to be converted into apex code or wrapper class
string jsonstring = ‘{“totalsForAllResults”: {“ga:users”: “2”}, “rows”:[[“San Francisco”,”358″,”375″],[“San Jose”,”358″,”375″],[“Mid Peninsula”,”358″,”375″],[“Greater Bay”,”358″,”375″],[“Los Angeles”,”358″,”375″]]}’
// now we convert json string into wrapper class using JSON.deserialize method
jsonWrapper Jsondatawrapper = (jsonWrapper)JSON.deserialize(jsonstring,jsonWrapper.class);
// you can use your data according to your need
for(List<String> str: Jsondatawrapper.rows)
{
system.debug( Integer.valueof(str[1]));
}
NOTE: You can convert json into any type like : list, string , integer . Its all depend on the format in which data is available in json . here i used wrapper and get rows from json and rows are in the form of List<list> so i take my wrapper variable name type as List<list> .</list</list
Hits: 5020