Deserialize JSON array into list of objects

apexjson

I'm getting a JSON array from a REST callout:

[{\"name\":\"Jan0\",\"lastName\":\"Test0\",\"id\":0},
 {\"name\":\"Jan1\",\"lastName\":\"Test1\",\"id\":1},
 {\"name\":\"Jan2\",\"lastName\":\"Test2\",\"id\":2},
 {\"name\":\"Jan3\",\"lastName\":\"Test3\",\"id\":3}]

This gives me an error:

 List<Object> objs = (List<Object>)JSON.deserializeUntyped(res.getBody());

FATAL_ERROR System.TypeException: Invalid conversion from runtime type String to List

Ouch. Did I serialize the JSON incorrectly, or am I doing a mistake at covnerting the JSOn to the List?

Best Answer

Looks like the payload got serialized twice somehow. Ideally you would fix that so it is serialized just once instead. However, you can fix it in the interim by deserializing first into a String, then into your List<Object>.

String payload = (String)JSON.deserializeUntyped(response.getBody());
List<Object> data = (List<Object>)JSON.deserializeUntyped(payload);