5

我正在尝试以某种方式解组 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"
      }

这是我想将此 Json 映射到的 Model 类:

public class Model{

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

    //Getters and Setter methods
}

所以在这里,我想要的是得到一个columns包含键的地图"MEMO_TEXT","MEMO_LINK","MEMO_DOB","MEMO_USERNAME","MEMO_CATEGORY","MEMO_UID"

Json 中的其余属性映射到各自的字段。

是否可以使用杰克逊图书馆的 ObjectMapper 来做到这一点?

4

3 回答 3

10

您可以使用 @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);
    }
}

此外,@JsonAnyGetter 确实“有点相反”,所以这应该以相同的方式序列化和反序列化。

于 2015-05-10T21:41:39.430 回答
1

实现您想要的几种方法之一是添加构造函数:

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

请注意,如果将其序列化回 JSON,则结构将与初始结构不同。

于 2015-05-08T12:04:47.857 回答
0

尝试使用 SerializerProvider。SerializerProvider 可以修改反序列化,启用自定义反序列化。

于 2015-05-07T13:14:25.067 回答