Take the 2-minute tour ×
Salesforce Stack Exchange is a question and answer site for Salesforce administrators, implementation experts, developers and anybody in-between. It's 100% free, no registration required.

I'm having so trouble deserializing a JSON stream that contains an array as the root:

[
    {
        "object": {
                     "property1":"000000",
                     "property2":"000000"
                  }
    },
    {
        "object": {
                     "property1":"000000",
                     "property2":"000000"
                  }
    }
]

I tried using JSON.deserializeUntyped and assigning to a Map, but I keep getting a "invalid conversion runtime type LIST to MAP". This method worked fine when I was dealing with single JSON objects, but loading multiples into an array trips this error. Should I be using a different type for deserialization?

share|improve this question
    
Delete comma after property2. (I deleted my answer to add this comment) –  SF_user Aug 19 at 15:18
    
Comma removed. This was just a quick example I threw together to get the idea across! –  Lee Harrison Aug 19 at 16:04

2 Answers 2

up vote 3 down vote accepted

You have to cast it into a List<Object>, and for each element in the list, you can access the values as a Map<Object,Object>.

share|improve this answer
    
Thanks! Seems so obvious now that I know what to do! –  Lee Harrison Aug 19 at 16:04

As well as containing the extra commas, the JSON you show is an array of objects. You have to type convert it in two steps:

String s = '[{"object": {"property1":"000000","property2":"000000"}},'
        + '{"object": {"property1":"000000","property2":"000000"}}]';

List<Object> l = (List<Object>) JSON.deserializeUntyped (s);
for (Object o : l) {
    Map<String, Object> m = (Map<String, Object>) o;
    System.debug('>>> m=' + m);
}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.