将json数组序列化为java对象

时间:2015-12-29 18:48:38

标签: java json serialization jackson

我有一个如下所示的JSON数组,我需要将它序列化到我的班级。我在项目中使用杰克逊。

[
    {
        "clientId": "111",
        "clientName": "mask",
        "clientKey": "abc1",
        "clientValue": {}
    },
    {
        "clientId": "111",
        "clientName": "mask",
        "clientKey": "abc2",
        "clientValue": {}
    }
]

在上面的JSON数组中,clientValue将包含另一个JSON对象。如何使用Jackson将我的上述JSON数组序列化到我的java类中?

public class DataRequest {
    @JsonProperty("clientId")
    private String clientId;

    @JsonProperty("clientName")
    private int clientName;

    @JsonProperty("clientKey")
    private String clientKey;

    @JsonProperty("clientValue")
    private Map<String, Object> clientValue;

    //getters and setters
}

之前我没有使用过jackson所以我不知道如何使用它将我的JSON数组序列化为Java对象?我在这里使用jackson注释来序列化东西,但不确定下一步是什么?

2 个答案:

答案 0 :(得分:1)

您可以创建如下所示的实用程序功能。您可能希望根据业务需要更改反序列化功能。就我而言,我不想在未知属性上失败=&gt; (FAIL_ON_UNKNOWN_PROPERTIES,false)

static <T> T mapJson(String body, 
                     com.fasterxml.jackson.core.type.TypeReference<T> reference) {
    T model = null;

    if(body == null) {
        return model;
    }

    com.fasterxml.jackson.databind.ObjectMapper mapper = 
         new com.fasterxml.jackson.databind.ObjectMapper();

    mapper.configure(com.fasterxml.jackson.databind.DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, 
                     false);
    try {
        model = mapper.readValue(body, reference);
    } catch (IOException e) {
        //TODO: log error and handle accordingly
    }

    return model;
}

您可以使用类似方法调用它,如下所示:

mapJson(clientValueJsonString, 
        new com.fasterxml.jackson.core.type.TypeReference<List<DataRequest>>(){});

答案 1 :(得分:1)

您可以使用内部类对象尝试@JsonAnyGetter@JsonAnySetter注释。 clientName也应该有String类型,而不是int。

public class DataRequest {

    private String clientId;

    private String clientName;

    private String clientKey;

    private ClientValue clientValue;

    //getters and setters
}

public class ClientValue {

    private Map<String, String> properties;

    @JsonAnySetter 
    public void add(String key, String value) {
        properties.put(key, value);
    }

    @JsonAnyGetter 
    public Map<String,String> getProperties() {
        return properties;
    } 

}
相关问题