I am trying to deserialize a JSON response.

public class CLiveExMarketPriceHistory{
public String lwin11;   //11227502005
public String lcurrency;    //GBP
public String priceFrom;    //2013-07-12
public cls_prices[] prices;
public class cls_prices {
    public String ldate;    //2013-07-12
    public Decimal marketPrice; //880
public static CLiveExMarketPriceHistory parse(String json){
    return (CLiveExMarketPriceHistory) System.JSON.deserialize(json, CLiveExMarketPriceHistory.class);

The JSON response is


The issue I am facing is that the JSON has attributes like date and currency which i am not able to use in my class as they are salesforce datatypes. I tried changing the class variables as lcurrency and ldate. But after deserialisation the values for these changed class variables are null as they don't match with the JSON response.

Any thoughts on how i can get values for the date and currency from JSON?

  • I recommend json2apex.herokuapp.com
    – Mike Chale
    Jan 28 '14 at 14:38
  • @Mike Chale can you confirm that json2apex can handle apex protected keywords ? I didn't know that. Jan 28 '14 at 14:41
  • @MikeChale i did use json2apex, the issue is with the protected keywords. Not sure how we can handle it
    – Prady
    Jan 28 '14 at 14:46
  • I was running through some of the previous posts and found this salesforce.stackexchange.com/questions/2276/… . Probably Daniel's answer there is what we need to do. I am leaving this question open for some more time if somebody has a better answer or probably somebody can close it as a duplicate question
    – Prady
    Jan 28 '14 at 14:51
  • Sorry, I missed that the problem is that a field is named date.
    – Mike Chale
    Jan 28 '14 at 15:07

You have two choices: JSON.deserializeUntyped or JSON.createParser. The former returns an object that operates like a map; you can call the get function, passing in a string, to return a value. The latter returns a parser that generates token events that you can use to parse the object.

Map<String, Object> data = (Map<String, Object>)JSON.deserializeUntyped(json);
String lwin11 = (String)data.get('lwin11');
String theCurrency = (String)data.get('currency');
Date priceFrom = Date.valueOf((String)data.get('priceFrom'));
List<Map<String, Object>> prices = (List<Map<String, Object>>)data.get('prices');
for(Map<String, Object> price: prices) {

You may have to play with the precise syntax, but examples are in the documentation.


You could use JSON.deserializeUntyped

Map<String, Object> m = (Map<String, Object>)

String lcurrency = m.get('currency'));

Another option, though it's not necessarily the best performance-wise, would be to "filter" the JSON response through a string-replace? I.e.

jsonInput = jsonInput.replace('"currency":', '"1currency":');

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