2

I have the following JSON structure

{  
"PLU":{  
  "high":"N/A",
  "low":"N/A",
  "percentChange":"0",
  "baseVolume":"0",
  "quoteVolume":"0"
},
"1ST":{  
  "high":"0.00033386",
  "low":"0.00033386",
  "percentChange":"0",
  "baseVolume":"1",
  "quoteVolume":"2"
},
"VSL":{  
  "high":"N/A",
  "low":"N/A",
  "percentChange":"0",
  "baseVolume":"0",
  "quoteVolume":"0"
},
"ARC":{  
  "high":"N/A",
  "low":"N/A",
  "percentChange":"0",
  "baseVolume":"0",
  "quoteVolume":"0"
},
"ICN":{  
  "high":"N/A",
  "low":"N/A",
  "percentChange":"0",
  "baseVolume":"0",
  "quoteVolume":"0"
 }
}

and using the below code I was able to deserialize and loop throught the values

Map<string,Object> meta = (Map<string,Object>) JSON.deserializeUntyped(JSON);


   for(String s : meta.keySet()){

      Map<string,Object> markets = (Map<string,Object>) meta.get(s);

       String high = (String)markets.get('high');
       String low  = (String)markets.get('low');
       //etc
       //rest of logic goes here

       }
    }

Question is.. is this there a more efficient/best practice way of doing it?

Thanks in advance for the help

1 Answer 1

8

You should define a data structure class for the sub-object

public class Subdata {
  public String high { get; set; }
  public String low { get; set; }
  public Decimal percentChange { get; set; } // If you are sure data is null or numerical but never string("N/A")
  ...

}

Then cast as this:

Map<String, Subdata> meta = (Map<String, Subdata>) JSON.deserialize(
    json, 
    Type.forName('Map<String, Subdata>')
);

To finally do:

for(String key : meta.keySet()){
  // key = VSL
  Subdata market = meta.get(key);

  String high = market.high;
  // ...
}

This way you avoid doing cast (String)market.get('high').

1
  • Thank you..that worked perfectly. I was initially trying to use the JSON2APEX tool but it was giving me a really complex structure to work with so this seems a lot more streamlined
    – JPG
    Mar 6, 2018 at 16:43

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .