I have a Map<String, Object> which contains a deserialized form of JSON. I would like to deserialize this into the fields of a POJO.
I can perform this using Gson by serializing the Map into a JSON string and then deserializing the JSON string into the POJO, but this is inefficient (see example below). How can I perform this without the middle step?
The solution should preferably use either Gson or Jackson, as they're already in use by the project.
Example code:
import java.util.HashMap;
import java.util.Map;
import com.google.gson.Gson;
public class Test {
public static void main(String[] args) {
Map<String, Object> innermap = new HashMap<String, Object>();
innermap.put("number", 234);
innermap.put("string", "bar");
Map<String, Object> map = new HashMap<String, Object>();
map.put("number", 123);
map.put("string", "foo");
map.put("pojo2", innermap);
Gson gson = new Gson();
// How to perform this without JSON serialization?
String json = gson.toJson(map);
MyPojo pojo = gson.fromJson(json, MyPojo.class);
System.out.println(pojo);
}
}
class MyPojo {
private int number;
private String string;
private MyPojo pojo2;
@Override
public String toString() {
return "MyPojo[number=" + number + ", string=" + string + ", pojo2=" + pojo2 + "]";
}
}