function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Kenji778Kenji778 

Generic JSON Deserializer

Hey all,

Being somewhat a java style programming language novice, this is something that escapes me. Say I don't know what kind of data is going to returned via a call to a remote webservice. All I know is that is is going to contain JSON encoded data. I don't know what fields may be there, or if it may also contain nested arrays, etc. Is there a way to just have a generic deserialzation process, without having to cast to a specifc class type? In ColdFusion for example, there is just a deserializeJson function which can take any kind of JSON string as long as it is valid and create a logical structure out of it. You have no need to know ahead of time anything about the structure of the JSON and it is extremely handy, and much more robust than having to manually define a data type for the expected return. Is this possible in Apex as well, or not due to the statically typed nature of the language?

SuperfellSuperfell

Yes, you can deserialize into general types like arrays and maps. see https://gist.github.com/1287653 for an example.

Kenji778Kenji778

Cool, I kind of thought that might work, but the question of sub arrays comes up. I would assume that would cause issues in that case?

Kenji778Kenji778

Ah yeah, looks like it can't quite handle sub arrays. EX

String j = '{ "father": "bobby", "kids":  [{"name":"jimmy"}, {"name":"janet"}] }';     
 Map<String, String> b = (Map<String,String>) JSON.deserialize(j, Map<String,String>.class);
System.debug(b);

 

 Dies. That's a bummer. So this work sgreat for 'flat' json, but heirachies are bad news.