3

How can "orderDetails" be extracted from the following JSON payload?

{
    "itemId": "111",
    "count": "20",
    "bookOrders": [
        {
            "bookName": "book1",            
            "bookId": "1234",
            "bookPrintDate": "2015-05-18",
            "orderDetails": {
                "chapter1": "description1",
                "chapter2": "description2"
            }
        },      
        {
            "bookName": "book2",            
            "bookId": "1111",
            "bookPrintDate": "2015-05-20",
            "orderDetails": {
                "chapter1": "description1",
                "chapter2": "description2"
            }
        }        
    ]
}

Thanks in advance.

8

Christian's answer is probably the quickest way to do that and it caters for more complex scenarios.

Most of the time I tend to use json2apex to generate the class and the parser for me. Depending on the case, sometimes it's more convenient and scalable.

1
  • Bachovski and Christian Deckert your responses were really helpful both the ways works, I think I need to figure out which one works better.
    – sfdc5000
    May 8 '15 at 20:29
6

You can use the build in JSON deserializer.

The easiest solution would look like this:

String jsonContent = [YOUR JSON CONTENT];
Object jsonObj = Json.deserialize(jsonContent);
List<Object> bookOrders =(List<Object>) ((Map<String, Object>)jsonObj).get('bookOrders');
for(Object bookOrder : bookOrders)
{
    System.debug(bookOrder.get(orderDetails));
}

Besides from using the json parser you can consider to use JSON Parser.

1
  • Thanks Chrstian Deckert your response helped me real well. Thanks you.
    – sfdc5000
    May 8 '15 at 20:30
1

Here is the JSON Parser way:

OrdDetails od;
JSONParser parser = JSON.createParser(jsonString);
while (parser.nextToken() != null) {
    if (parser.getText() == 'orderDetails') {
        while (parser.nextToken() != null) {
            if (parser.getCurrentToken() == JSONToken.START_OBJECT) {
                    od = ( OrdDetails)parser.readValueAs(OrdDetails.class);
                    break;
            }
        }
    }
}

System.debug(od);

This depends on there being an OrderDetails object like this:

class OrdDetails{
    String chapter1;
    String chapter2;
}

Looking at the code of the other questions, in this case definitely, I think using deserializeUntyped is going to be quicker and easier to read. As you can see, in my code, there are two nested while loops - not a very maintainable way of parsing JSON! Anyway, it's here as the other way to do it.

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.