0

I have an apex method that is calling an order detail api and returning a JSON response to the front end via something like this:

...
HttpResponse res = h.send(req);
Map<String, Object> orderDetailJson = (Map<String, Object>) System.JSON.deserializeUntyped(res.getBody());

Now I want to insert a separate key/value pair into that response. For example, let's say the orderDetailJson above is this:

{
    "cancelable": true,
    "order": {
        "orderId": "123456789",
        "orderItems": [{...}, {...}]
    }
}

I want to add order.storeName = "Sears", so that the final orderDetailJson looks like this

{
    "cancelable": true,
    "order": {
        "orderId": "123456789",
        "orderItems": [{...}, {...}],
        "storeName": "Sears"
    }
}

How can I do that?

1
2

It can get complicated if you want to add something deeper down than the top level, because you end up having to do some casting into other collections.

For example, to add an order item, you have to do something like:

Map<String, Object> orderDetailJson = (Map<String, Object>) System.JSON.deserializeUntyped(res.getBody());
Map<String, Object> orderEntry = (Map<String, Object>)orderDetailJson.get('order');
List<Object> orderItems = (List<Object>)orderEntry.get('orderItems');
orderItems.add(new Map<String, Object>{
  'quantity' => 5,
  'productCode' => '12345'
});

Not terribly bad, but you have to understand the nature of your data structures to get anywhere. Casting to the wrong type will give you a runtime exception.

In your specific case, we want to add a value to the order, so we would write:

Map<String, Object> orderEntry = (Map<String, Object>)orderDetailJson.get('order');
orderEntry.put('storeName','Sears');
0
    Map<String, Object> objectsByKey = (Map<String, Object>) System.JSON.deserializeUntyped( res.getBody() );
    Map<String, Object> orderByKey = (Map<String, Object>) objectsByKey.get('order'); // Extract the node you want to add fields from the main object
    
    orderByKey.put('storeName', 'Sears'); // Add values
    objectsByKey.put('order', orderByKey); // Replace the object into the first map
        
    system.debug('objectsByKey --> ' + JSON.serialize( objectsByKey ) );
1
  • 1
    Values are by reference, so you don't need to put the value back into the map.
    – sfdcfox
    Jul 8 at 23:12

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.