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 + "]"; } }
A quick look at how to convert a POJO from/to a Map<K, V> with Jackson: // Create ObjectMapper instance ObjectMapper mapper = new ObjectMapper(); // Converting POJO to Map Map<String, Object> map = mapper. convertValue(foo, new TypeReference<Map<String, Object>>() {}); // Convert Map to POJO Foo anotherFoo = mapper.
We are using writeObject() method of ObjectOutputStream to serialize HashMap in Java. In the following program, we save the hashmap content in a serialized newHashMap file. Once you run the following code, a newHashMap file will be created. This file is used for deserialization in the next upcoming program.
Use Object#toString() . String string = map. toString();
Using toString() method The string representation of a map consists of a list of key-value pairs enclosed within curly braces, where the adjacent pairs are delimited by a comma followed by a single space and each key-value pair is separated by the equals sign ( = ). i.e., {K1=V1, K2=V2, ..., Kn=Vn} .
Using Gson, you can turn your Map into a JsonElement
, which you can then parse in exactly the same way using fromJson
:
JsonElement jsonElement = gson.toJsonTree(map); MyPojo pojo = gson.fromJson(jsonElement, MyPojo.class);
This is similar to the toJson
method that you are already using, except that it avoids writing the JSON String representation and then parsing that JSON String back into a JsonElement before converting it to your class.
In Jackson
you can use convertValue method. See below example:
mapper.convertValue(map, MyPojo.class);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With