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.

    In .Net you would prepend with '@'. Does Apex have something similar?

    Not that I was able to find but I'm really hoping that someone will be able to correct me.

    Is it an option to deserialize as Map?

    it wasn't in this case since I wanted to deserialize into fairly complex objects and going through the deserializeuntyped map would have been painful. I ended up using the string replace and it worked fairly well.

  • 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

License under CC-BY-SA with attribution

Content dated before 7/24/2021 11:53 AM

Tags used