Convert a Map<String, String> to a POJO
Well, you can achieve that with Jackson, too. (and it seems to be more comfortable since you were considering using jackson).
Use ObjectMapper
's convertValue
method:
final ObjectMapper mapper = new ObjectMapper(); // jackson's objectmapper
final MyPojo pojo = mapper.convertValue(map, MyPojo.class);
No need to convert into JSON string or something else; direct conversion does much faster.
A solution with Gson:
Gson gson = new Gson();
JsonElement jsonElement = gson.toJsonTree(map);
MyPojo pojo = gson.fromJson(jsonElement, MyPojo.class);
if you have generic types in your class you should use TypeReference
with convertValue()
.
final ObjectMapper mapper = new ObjectMapper();
final MyPojo<MyGenericType> pojo = mapper.convertValue(map, new TypeReference<MyPojo<MyGenericType>>() {});
Also you can use that to convert a pojo to java.util.Map
back.
final ObjectMapper mapper = new ObjectMapper();
final Map<String, Object> map = mapper.convertValue(pojo, new TypeReference<Map<String, Object>>() {});