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
Best Answer
Yep, this resource is nailed by a cross-origin restriction.
Inspecting the Network tab will show if the request is aborted.
When you load things with a relative URL, jQuery doesn't actually know where the final endpoint will live. The response may redirect jQuery off your current domain to (eg) the Visualforce content domain. But it must choose a request strategy (same-domain / cross-domain) at the time you call the function.
The ultimate same-domain or a cross-domain nature of the request is not known until the response comes back ;-) the difference between
$.getJson
and$.ajax
is that one of them may not handle the redirect well with the default options.