JSON中的差异ObjectMapper readValue解析 - 有时给出Null

时间:2014-09-09 10:45:45

标签: java json spring jackson

使用ObjectMaper的readValue()解析json字符串时,我遇到了一个奇怪的情况。我使用Jackson 2.4.1和Spring 4.0.6。 问题是,当输入到readValue()时,相同的json字符串有时会给出null,有时会给出有效对象。
JSON字符串

{"productGroupInfoTransport":    {"groupId":36,"range":"LMEURSMA","productType":"LMFE","status":"ANNOUNCE","regionsList":[],"productsList":[],"groupName":"Bright Start test"}}

代码:

public Object getData(String jSONObject, String action, String module)
        throws Exception {

    ObjectMapper mapper = new ObjectMapper();
    mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,
            false); 
    mapper.configure(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES,
            false); 
    mapper.configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT,
            false); 
    //mapper.configure(SerializationConfig.   WRITE_NULL_PROPERTIES, false);
    String transport = null;

    if (jSONObject.contains(ERROR)) {

        transport = "Exception";

        throw new Exception("Unable to read Data");
    } else {

        transport = getTransport(action, module);
    }

    Object transportObject = null;

    transportObject = mapper.readValue(jSONObject, getTransport(transport));

    return transportObject;

}

ProductTransport:

package com.leggmason.lmEPAM.transport;

import java.util.List;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.leggmason.lmEPAM.model.ProductGroupModel;

public class ProductGroupTransport extends EPAMTransport<ProductGroupModel> {

@JsonProperty("productGroupInfoTransport")
protected ProductGroupModel modelObject;

@JsonProperty("productGroupTransport")
protected List<ProductGroupModel> data;

@JsonProperty("productGroupTransport")
@Override
public List<ProductGroupModel> getListData() {
    return this.data;
}

@JsonProperty("productGroupTransport")
@Override
public void setData(List<ProductGroupModel> data) {
    this.data = (List<ProductGroupModel>) data;

}

@Override
public String getModule() {

    return null;
}

@JsonProperty("productGroupInfoTransport")
@Override
public ProductGroupModel getObject() {
    return this.modelObject;
}

@JsonProperty("productGroupInfoTransport")
public void setObject(ProductGroupModel modelObject) {
    this.modelObject = modelObject;

}

@Override
public void setObject(Object modelObject) {
    // TODO Auto-generated method stub

}

}

在上面的代码中传递JsonString时,有一次ProductTransposrt将使用Object正确填充其modelObject,但是当我重新启动服务器时,相同的JSON字符串将在解析后将modelObject设置为null。我不明白为什么。谢谢你的帮助。

1 个答案:

答案 0 :(得分:0)

您可以尝试使用以下代码来解析json对象

JSONObject obj = new JSONObject(jSONObject);
JSONArray array = obj.getJSONArray("productGroupInfoTransport");
System.out.println(array.getJSONObject(0).getString("groupId"))

现在您可以正确解析json字符串。 仅解析json字符串可能会有所帮助。