0

I'm sure there has to be something small here that I'm missing. I have JSON array of values

[
    {
    _id : "55d78226726b611100aaf741",
    value1: 1,
    value2: 2
    }, 
    {_id: "55d66226726b611100bbf741",
     value1: 1, 
     value2: 2
    },
     etc....
    ]

Here is the casting that I'm doing when I make the api call. 

    System.debug(response.getBody());
            List<Json2Apex> equiMap = (List<Json2Apex>) JSON.deserialize(string.valueOf(response.getBody()), List<Json2Apex>.class);
            String value = (String)equiMap.get(1).x_id; 
            System.debug(value); 


I can see the value the _id value is present in the first `System.debug`, but in the second `System.debug` it shows as null. 

For simple lists like this, should JSON2Apex not be used? Thanks for the help. 

1
  • Can you provide a sample response.getBody()? Mar 4 '21 at 3:32
2

You can't use reserved or illegal names with JSON.deserialize and a template class. You need to enable the use of "explicit parsing" in JSON2Apex, which generates a longer JSON parser in the form of a JSONParser script, which you then call as:

Json2Apex equiMap = Json2APex.parse(response.getBody().toString());

In other words, JSON.deserialize(String, Class) doesn't use any conventions; it can't automatically convert _id to x_id, so you need to use the parse method provided.

In your case, you may find it easier to instead generically deserialize your body:

List<Object> equiList = (List<Object>)JSON.deserializeUntyped(response.getBody().toString());
for(Object equiItem: equiList) {
  Map<String, Object> equiMap = (Map<String, Object>)equiItem;
  System.debug(equiMap.get('_id'));
}
1
  • Thanks, I need to get a better understanding of casting into objects and when to use it. Thanks again.
    – thinker
    Mar 4 '21 at 14:34
0

It turned out that using explicit parsing was not necessary. The solution above is still valid from @sfdcfox. This answer is another way of accomplishing it.

When Apex2JSON publishes, there is a parse method:


public static List<Apex2JSON> parse(String json) {
        System.JSONParser parser = System.JSON.createParser(json);
        return arrayOfApex2JSON(parser);
    }

You can use this method like this:


List<Apex2JSON> apexList = Apex2JSON.parse(response.getBody());

for (Apex2JSON a : apexList) {
    // Do stuff 
}

^^^^ The reason that this works is because the parse method in the JSON2Apex class returns a List of JSON2Apex objects. I had not thought about using the methods in the JSON2Apex generated class.

Again the casting option works as well up above from SFDCfox.

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.