title: Jackson - Mapping an Object type field of json representation of class1 to class2
body: <p>I have two POJOs defined :</p>
  
  <p>Class1 -</p>
  
  <pre><code>public class Class1 {
  
          Map&lt;String, Object&gt; param1 = new HashMap&lt;String, Object&gt;();
          Map&lt;String, Object&gt; param2 = new HashMap&lt;String, Object&gt;();
          Object body;
  
          // getters-setters...
  }
  </code></pre>
  
  <p>Class2 -</p>
  
  <pre><code>public class Class2   {
  
    private String name = null;
    private String description = null;
    private List&lt;Integer&gt; data = new ArrayList&lt;Integer&gt;();
  
    // getters-setters...
    }
  </code></pre>
  
  <p>The body field is dynamic so I have made it an Object type. I generate the Class2 Pojo at run time using <code>swagger codegen</code>. So basically <code>body</code> object represents the Class2. Class1 is the fixed class and al the fields are known.</p>
  
  <pre><code>json -
  {
    "param1" : {
      "id" : 132
    },
    "param2" : {
      "address" : "String"
    },
  
    "body" : {
      "name" : "value",
      "description" : "value",
      "data" : [ ]
    }
  }
  </code></pre>
  
  <p>I can deserialize above json for Class1 : </p>
  
  <pre><code>ObjectMapper mapper = new ObjectMapper();
  Class1 ij = mapper.readValue(new File(path_of_above_json), Class1.class);
  param1 = ij.getParam1();
  param2 = ij.getParam2();
  Object body = ij.getBody();
  </code></pre>
  
  <p>I want to map the body field to Class2. I can do the same with gson :</p>
  
  <pre><code>Class2 body1 = new Class2();
  Gson gson = new GsonBuilder().registerTypeAdapter(Class2.class, new ResponseBodyDeserializer&lt;Class2&gt;()).create();
  ObjectMapper mapper = new ObjectMapper();
  InputStream in = MainClass.class.getResourceAsStream(path_of_above_json);
  BufferedReader r = new BufferedReader(new InputStreamReader(in));
  body1 = gson.fromJson(r , Class2.class);
  </code></pre>
  
  <p>with additional class ResponseBodyDeserializer -</p>
  
  <pre><code>class ResponseBodyDeserializer&lt;T&gt; implements JsonDeserializer&lt;T&gt;
  {
      @Override
      public T deserialize(JsonElement je, Type type, JsonDeserializationContext jdc)
          throws JsonParseException
      {
          // Get the element from the parsed JSON
          JsonElement content = je.getAsJsonObject().get("body");
  
          // Deserialize it
          return new Gson().fromJson(content, type);
      }
  }
  </code></pre>
  
  <p>Can we achieve the same thing with Jackson so as to avoid this additional class?</p>
  
  <p>Thank you!</p>