[SalesForce] How to merge multiple Map/JSON Object into One Map

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"}}

Best Answer

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');