title: Merge/Extend JSON Objects using Gson in Java
body: <p>Oftentimes, I have a need to merge two JSON Objects (similar to the way jQuery's <a href="http://api.jquery.com/jQuery.extend/" rel="noreferrer"><code>$.extend()</code></a> works). However, the Gson library has no built in functionality and they have said <a href="https://github.com/google/gson/issues/166" rel="noreferrer">they won't implement it</a>.</p>
  
  <p>Doing something like:</p>
  
  <pre><code>private void merge(JsonObject firstObj, JsonObject secondObj){
      for(String keyInSecondObj : secondObj.entrySet().keySet()) {
        if(!firstObj.has(keyInSecondObj )){
          firstObj.add(secondMap.get(keyInSecondObj));
      }
  }
  </code></pre>
  
  <p>Is too simple because it doesn't handle recursively merging JsonObjects, doesn't handle conflicts when the key exists in both maps, and has no special handling for non-primitive values such as Arrays.</p>
  
  <p>I failed to find any pre-built solutions to do this. I would prefer to use something that has been thoroughly tested instead of writing my own method, but  it must be <strong>Gson</strong> (not Jackson or other).</p>
  
  <p><em>Edit: I ended up writing my own implementation as have added as an <a href="https://stackoverflow.com/a/34092374/261088">answer to this question</a></em></p>
  
  <p><a href="https://stackoverflow.com/questions/21160337/how-can-i-merge-two-jobject">This question</a> is <strong>not</strong> a duplicate because it's not using Gson (or Java for that matter).</p>