简体   繁体   English

使用Jackson ObjectMapper将Json的一部分转换为HashMap

[英]Convert a part of Json to HashMap using Jackson ObjectMapper

I am trying to unmarshall a json file in a way such that few properties of Json are mapped into a HashMap that is present in my model class.Rest of the properties are mapped to the respective fields of the class.Please find the Json below: 我试图以一种方式解组json文件,使得Json的少数属性被映射到我的模型类中存在的HashMap。属性的重置被映射到类的相应字段。请在下面找到Json:

{
         "_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 to which I want to map this Json: 这里是我要映射这个Json的Model类:

public class Model{

    private int                              _id;
    private String                           name;
    private int                              age
    private HashMap<String, String> columns;

    //Getters and Setter methods
}

So here, what i want is to get a map columns that contains keys "MEMO_TEXT","MEMO_LINK","MEMO_DOB","MEMO_USERNAME","MEMO_CATEGORY","MEMO_UID" 所以在这里,我想要的是获得一个包含键"MEMO_TEXT","MEMO_LINK","MEMO_DOB","MEMO_USERNAME","MEMO_CATEGORY","MEMO_UID"的地图columns

and rest of the properties in Json are mapped to their respective fields. Json中的其余属性映射到它们各自的字段。

Is it possible to do this using ObjectMapper of Jackson Library? 是否可以使用杰克逊图书馆的ObjectMapper来做到这一点?

You can use @JsonAnySetter to annotate a method to be called for "other" properties: 您可以使用@JsonAnySetter来注释要为“其他”属性调用的方法:

@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);
    }
}

Also, @JsonAnyGetter does "kind of the reverse", so this should serialize and deserialize the same way. 此外,@ JsonAnyGetter做了“反向”,所以这应该以相同的方式序列化和反序列化。

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());
    }
}

Be aware that if you serialize it back to JSON the structure will be diffrent than the initial one. 请注意,如果将其序列化为JSON,则结构将与初始结构不同。

Try using a SerializerProvider. 尝试使用SerializerProvider。 A SerializerProvider can modify the deserialization, enabling custom deserialization. SerializerProvider可以修改反序列化,从而启用自定义反序列化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用 Z7930C951E609E4161E82EDZ26004 将 Java HashMap 序列化到 JSON - Serliazing Java HashMap to JSON using Jackson ObjectMapper 如何使用 Jackson 的 ObjectMapper 将下面的 JSON 转换为 POJO - How to convert below JSON to POJO using ObjectMapper of Jackson 使用jackson将json对象的List转换为hashmap - Convert a List of json object to hashmap using jackson 使用Jackson将Json子对象转换为HashMap - Convert Json subobject to a HashMap with Jackson 使用 Jackson 的 ObjectMapper 的 JSON 对象顺序 - Order of JSON objects using Jackson's ObjectMapper 将JSON数组转换为HashMap <String,Object> 使用杰克逊解析器 - Convert a JSON array to a HashMap<String,Object> using jackson parser 如何使用Jackson将JSON对象转换为Java HashMap? - How to convert JSON Object to Java HashMap using Jackson? 如何使用杰克逊将json数组转换为Java hashmap - How to convert json array to java hashmap using jackson 如何使用Jackson / ObjectMapper将注释(其所有diff属性)转换为JSON对象? - How convert an annotation (all its diff properties) into a JSON object using Jackson/ObjectMapper? Spring Boot 测试:使用 Jackson ObjectMapper 将模型转换为 JSON 字符串时 UserControllerTest 失败 - Spring Boot Test: UserControllerTest Fails When Using Jackson ObjectMapper To Convert Model To JSON String
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM