1

I am trying to build a json out of List of Maps but I need to merge few maps together when matching key is found.

How can I merge few Apex Map Object values ?

For example:

Map<String,Object> parent1 = new Map<String,Object>{
      'field1' =>  'value'
    };
Map<String,Object> root1 = new Map<String,Object>{
      'root' => parent1
};
Map<String,Object> parent2 = new Map<String,Object>{
      'field2' =>  'value'
    };
Map<String,Object> root2 = new Map<String,Object>{
      'root' => parent2
};

If Ill add each Map root1 and root2 to a List:

List<Map<String,Object>> listOfMap =new List<Map<String,Object>>();  
listOfMap.add(root1);
listOfMap.add(root2);

Results will look like this :

[{"root":{"field1":"value"}},{"root":{"field2":"value"}}]

Which is closer, But what I'm trying to do is to merge this results into one Object.

For example my end result should look like :

{
    "root": {
      "field1": "value",
      "field2": "value"
    }
  }

If ill place those 2 Maps using putAll() - Instead of appending the values I will always get the last.

{"root":{"field2":"value"}}
2

Something like this?

Map<String,Object> jsonMap = new Map<String,Object>{'root'=> new Map<String,Object>{'field1'=>'value','field2'=>'value'}};
System.debug(JSON.serialize(jsonMap));

Your parent map key is root, so if you wanna add field3, you can

((Map<String,Object>)jsonMap.get('root')).put('field3','value');
2

You need to be doing putAll() on the child object of the root that you want to keep. That method does not do a recursive merge.

Given your examples, you'd want to do

root1.get('root').putAll(root2.get('root'));

Then, root1 would contain its own fields plus the fields from root2.

Since you've typed your objects as Map<String, Object>, you'd have to cast the return value of get():

(Map<String, Object>)root1.get('root').putAll((Map<String, Object>)root2.get('root'));
  • yes it makes sense but this is not working - get the following Error => Method does not exist or incorrect signature: void putAll(Object) from the type Object – sfdx bomb Dec 1 '18 at 1:51
  • Sorry, I forgot you were using generically-typed objects. – David Reed Dec 1 '18 at 2:21

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.