Convert Json Part to HashMap with Jackson ObjectMapper

I am trying to unzip a json file so that some Json properties are displayed in the HashMap, which is present in my model class. The reserve of properties is mapped to the corresponding fields of the class. Json below:

{ "_id":2, "Name":"xyz", "Age":20, "MEMO_TEXT":"yyy", "MEMO_LINK":"zzz", "MEMO_DOB":"", "MEMO_USERNAME":"linie orange", "MEMO_CATEGORY":2, "MEMO_UID":"B82071415B07495F9DD02C152E4805EC" } 

And here is the Model class that I want to apply this Json to:

 public class Model{ private int _id; private String name; private int age private HashMap<String, String> columns; //Getters and Setter methods } 

So, here I want to get a columns map that contains the keys "MEMO_TEXT","MEMO_LINK","MEMO_DOB","MEMO_USERNAME","MEMO_CATEGORY","MEMO_UID"

and other properties in Json are mapped to the appropriate fields.

Can this be done using Jackson's ObjectMapper library?

+5
source share
3 answers

You can use @JsonAnySetter to annotate a method that should be called for "other" properties:

 @Test public void partial_binding() throws Exception { Model model = mapper.readValue(Resources.getResource("partial_binding.json"), Model.class); assertThat(model.name, equalTo("xyz")); assertThat(model.columns, hasEntry("MEMO_TEXT", "yyy")); assertThat( mapper.writeValueAsString(model), json(jsonObject() .withProperty("Name", "xyz") .withProperty("MEMO_TEXT", "yyy") .withAnyOtherProperties())); } public static class Model { @JsonProperty private int _id; @JsonProperty("Name") private String name; @JsonProperty("Age") private int age; private HashMap<String, String> columns; @JsonAnyGetter public HashMap<String, String> getColumns() { return columns; } public void setColumns(HashMap<String, String> columns) { this.columns = columns; } @JsonAnySetter public void putColumn(String key, String value) { if (columns == null) columns = new HashMap<>(); columns.put(key, value); } } 

In addition, @JsonAnyGetter does a "reverse look", so it should serialize and deserialize the same way.

+10
source

One of several ways to achieve what you want is to add a constructor:

 @JsonCreator public Model(Map<String, Object> fields) { this._id = (int) fields.remove("_id"); this.name = (String) fields.remove("Name"); this.age = (int) fields.remove("Age"); this.columns = new HashMap<String, String>(); for (Entry<String, Object> column : fields.entrySet()) { columns.put(column.getKey(), column.getValue().toString()); } } 

Keep in mind that if you serialize it back to JSON, the structure will be different from the original.

+1
source

Try using SerializerProvider. SerializerProvider can change the deserialization, which allows you to customize the deserialization.

0
source

All Articles