2

While playing with the JSON parser I encountered a use case (described below in detail) for which using JSON.deserialize(JSONResponse, SampleParent.class) method for parsing doesn't work.

Below is the use case:

public class SampleParent{

    public String a {get;set;}
    public String b {get;set;}
    public String c {get;set;}
    public String d {get;set;}
    public SampleChild test {get;set;}

    public SampleChild{ 
          // in response, for this class doesn't know about the fields. in each and 
          // every response the fields are changing i.e. it is dynamic with no structure
    }

}

How to handle such response using JSON.deserialize and store it in Apex class variable? Actually I want to store such response in String variable.

Response :- 1

{
     "a": "Sometext",
      "b": "Sometext",
       "c": "Sometext",
        "d": "Sometext",
      "test": {
        "Data1": {
          "score": 2
        },
        "Data2": {
          "score1": 1
        },
        "Data3": {
          "score1": 2
        }
      }

 }

Response :- 2

 {
     "a": "Sometext",
      "b": "Sometext",
       "c": "Sometext",
        "d": "Sometext",
      "test": {
        "Data50": {
          "score12": 2
        }       
      }
}

Actually I want to store such response in String variable like a = '{ "Data50": {"score12": 2}}'

Can we handle this use case in Salesforce ?

Any pointers on this would be highly appreciated. Thanks in Advance.

4

JSON.deserializeUntyped is for doing exactly the type of untyped, dynamic parsing you describe. Your JSON becomes a Map which you navigate (code example included in doc page).

System.JSONParser, as mentioned by tomlogic, would also get you where you need to go although it will probably end up being more code.

  • Hi, how to parse JSON response which contain both static (we know the object's fields) and dynamic objects (we don't know the object's fields.) – FlightPlan Feb 6 '13 at 23:03
  • My use case is like below public class Sample{ public String a {get;set;} public Sample1 test {get;set;} public class Sample1{ // in response, for this class dont know about the fields }} How to handle such response using JSON.deserialize /JSON.deserializeUntyped and map it to Apex class? Any pointer's on this would be highly appricate. Thanks in Advance. – FlightPlan Feb 6 '13 at 23:15
2

Take a look at the System.JSONParser methods, as a way to parse a JSON string one element at a time.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.