If you know the structure of the JSON before you get it then the easiest way is to create a class to define the Object.
For Example, given the following JSON String
{
"id" : "someID",
"street" : "someStreet",
"listOfClass" : [
{
"myVar" : "test"
}
]
"myArray" : ["1","2","3"]
}
Define the object as such:
public class myJSONClass{
public string id;
public string street;
public listOfClass[] listOfClass;
public String[] myArray;
public class listOfClasses{
public String myVar;
}
}
Do not think of it as a class to clutter your other classes, think of it as an object definition (what it is)
Then simply deserialize as follows:
myJSONClass obj = (myJSONClass)JSON.deserialize(JSONSTRING,myJSONClass.class);
Where it becomes tricky is when you are using reserved names or an unknown structure.
In most of those cases you need to use the JSON Parser methods to parse the string.The exception is if you only have a FEW reserved names you can replace them as such
JSONString = JSONString.replace('name','name_Z');
then define the property in the class as name_Z
. It will save a lot of work.
Back to your original point, if you have no class you can deserialize as such:
Map<String,Object> obj = JSON.deserializeUntyped(JSONString);
Then you can just cast everything to strings:
Map<String,String> results = New Map<String,String>();
for(String key : obj.keySet()){
results.put(key,string.valueOf(obj.get(key));
}
However in this case you lose the structure. For example, in your string if you have lists, arrays, etc, you get the string representation of the values and not the actual structure. More useful to define a class and work with it.
Note You do not have to have everything defined in the class to deserialize unless you use deserializeStrict. So if in my first example you removed public String id
it would still deserialize
In all the above examples, make sure to check for nulls and errors
As mentioned in comment, you have to deserialize the JSON and create the EncodeURL string from it.
class Attribute {
public String first_name{get;set;}
public String last_name{get;set;}
public String email{get;set;}
public String Id{get;set;}
public String getEncodedURL()
{
String encodedURL = 'id='+((null != this.id)?this.id:'')
+'&first_name='+((null != this.first_name)?this.first_name:'')
+'&last_name='+((null != this.last_name)?this.last_name:'')
+'&email='+((null != this.email)?this.email:'');
return encodedURL;
}
}
class Result {
public Attribute attributes {get;set;}
}
String jsonStr = '{"attributes": {"first_name":"A","last_name":"c","email":"te@gmail.com","Id":"003S000000vz81JIAQ"}}';
Result rs = (Result)JSON.deserializeStrict(jsonStr, Result.class);
System.debug('JSON ##'+jsonStr);
System.debug('RESULT ##'+rs);
System.debug('EncodeURL ##'+rs.attributes.getEncodedURL());
Best Answer
Let me google that for you...
https://www.google.co.uk/search?q=salesforce+json+deserialize
The class is called JSON, and the method is:
So you use it as: