[SalesForce] Trailhead Apex Super Badge JSON Parsing

Working on the Trailhead Apex Super Badge….

There is a section that requires writing a rest callout that returns a chunk of JSON that you are to use to update Product2 records with.

Reduced Chunk of JSON:

[{"_id":"55d66226726b611100aaf741","replacement":false,"quantity":5,"name":"Generator 1000 kW","maintenanceperiod":365,"lifespan":120,"cost":5000,"sku":"100003"},
{"_id":"55d66226726b611100aaf742","replacement":true,"quantity":183,"name":"Cooling Fan","maintenanceperiod":0,"lifespan":0,"cost":300,"sku":"100004"},
more records...]

A couple of issues… First trying to deserialize into a wrapper class with a field named _id will not compile. It gives the following error:

no viable alternative at character '_'

So I did a no-no just to get going and replaced all _id with id to get it to compile and deserialize.

Second issue (after reforming the JSON structure) is that none of the JSON records have a name. I can deserialize them into a list of generic Object's, but I then am unable to cast them to anything. It gives the following error:

Invalid conversion from runtime type

So again I cheated the JSON and added a jsonString = '{"recordsList":' + jsonString + '}'; so that I could generate a JSON2Apex wrapper.

I feel like either I am missing some basic concepts or whoever came up with this didn't actually have anybody come in and try and complete it behind them???

Best Answer

I'm a conflicted in answering this. If I give you too much detail it will make it too easy for others to complete the module (I.e. I shouldn't just dump my entire WarehouseCalloutService implementation). If I give you too little it won't be sufficient to answer your question.

My suggestions that hopefully find the right balance:

  1. Use https://json2apex.herokuapp.com/ to get the definition of the Equipment that you can parse from the JSON.
  2. Examine what is generated by the API and figure out what you do and don't need. You might not need all the fields the JSON returns. Cough Maybe even ones that are a bit problematic Cough.
  3. There are some really good examples of how to parse a JSON string and Deserialize it into objects in the docs.

From my pass through the badge I didn't encounter the problem you are having with the name. Maybe double check your code that is altering the _id values? I didn't need to do any post processing on the JSON response. It went fine as direct input into the JSON parsing.

Related Topic