[SalesForce] How to read JSON value of field

I have a Custom Object named AppConfig__c and a field named Config__c. In the field I have value as a JSON format. How can I read the value of the JSON field?
Below is an example field value:

{"SFObjectNames":[{"Account":{"SFFieldNames":["Industry","Type"]}},{"Addresses":{"SFFieldNames":["Coordinates__c"]}}]}

I have to read this value in Apex class. How can I get the value of SFFieldNames?

Best Answer

You have a couple options here, if the code will always return the same structure you can create a strongly typed class that will allow you to get the values you want. This tool will parse the json for you and create a class http://json2apex.herokuapp.com/

which results in this.

public class JSON2Apex {

        public class Account {
            public List<String> SFFieldNames;
        }

        public List<SFObjectNames> SFObjectNames;

        public class SFObjectNames {
            public Account Account;
            public Account Addresses;
        }


        public static JSON2Apex parse(String json) {
            return (JSON2Apex) System.JSON.deserialize(json, JSON2Apex.class);
        }
    }

You can call JSON2Apex myClass = JSON2Apex.parse( jsonString) which will parse the json and you can reference it in code.

Another way is to use the JSON class and do System.JSON.deserializeUntyped(json); which returns an Object and then you can cast loop over the object and cast the object to a Map if needed. This is a little more difficult in parsing and if you can use a Strongly Typed class because the structure won't change much, I would recommend that.

Edit: Adding looping for deserializedUntyped

List<Object> newList = List<Object>JSON.deserializeUntyped( jsonString);
for( Object o : newList) {

  Map<String, Object> castedObject = (Map<String, Object>)o;
  List<Object> sffFieldNames = o.get('SFObjectNames');

  // returns "[{"Account":{"SFFieldNames":["Industry","Type"]}},{"Addresses":{"SFFieldNames":["Coordinates__c"]}}]"
  for( Object o1 : sffFieldNames) {

    Map<String, Object> newCast = (Map<String, Object>)o1;
    Object acct = o.get('Account');
    // returns "{"SFFieldNames":["Industry","Type"]}}
  }
}

Basically, the you need to loop over the object, and you can cast to a Map and then you can get the key which returns the object value. and because you have nested array's you'll need to do this multiple times. Might be worth doing some sort of recursion, so it's not hardcoded.

Related Topic