Multi Level Nested JSON Parsing with Apex Salesforce

Master picture Master · Sep 5, 2014 · Viewed 8.8k times · Source

Can I parse Multi-Level nested JSON structure in APEX Salesforce, like we do in Java with GSON and Jackson libraries?

{
   "key1":"value1",
   "key2":{

          "key3":"value3",
          "key4":{
                 "key5":"value5"
           }

    }
}

I have already explored this.

Parsing JSON in Apex Salesforce

But I want a generic solution which will parse any JSON to the required Apex Object.

Answer

kmb picture kmb · Sep 8, 2014

You can using the serialize/deserialize methods of the JSON class in Apex:

https://www.salesforce.com/us/developer/docs/apexcode/Content/apex_class_System_Json.htm

You'll need to construct an Apex class based on your input JSON, but there's even a handy tool to do it:

http://json2apex.herokuapp.com/

Unfortunately however, you're limited by the depth of the Apex classes. I think after key4 in your example, you're back to parsing it manually.

One thing to consider is building a partial model in Apex, then hydrating any deeper nested objects you need using the parser.