How do you deserialize json properties that are reserved words in apex?

Is there any way to deserialize JSON into an object using JSON.deserialize if some of the property names in the JSON are reserved words in apex? I want to do something like this:

string jsonString = '{"currency" : "ABC"}';
public class JSONResult
    public string currency;
JSONResult res = (JSONResult) JSON.deserialize(jsonString, JSONResult.class);

but of course I get an error that the identifier name is reserved.


There are 2 ways that you could solve this problem, neither of them is exactly what you’re looking for, but I think it’s the best apex offers.

  1. Perform a string replace on the json string, the implications of this is unintended replacement of valid text inside a string, but this could be mitigated if the form of the json is as you’ve supplied "currency": "ABC" you could string replace:

    jsonString.replace('"currency":', '"currency_x":');

  2. The other is a lot more painful, it would require you to parse the json yourself using the JSON Parser methods. This will be a lot more accurate, but if the definition of the json changes you will have to rewrite your solution

Source : Link , Question Author : Greg Grinberg , Answer Author : Community

Leave a Comment