使用org.codehaus.jackson反序列化JSON字符串

时间:2013-04-10 07:12:11

标签: java spring spring-mvc

我是序列化和反序列化JSON的新手。

我有值

的字符串
String json = [{"Area":"LoremIpsum","Quantity":1500,"isSubArea":false},
{"Area":"LoremIpsum","Quantity":700,"isSubArea":false}];

我想要反序列化,我使用了Jackson的ObjectMapper来反序列化

ObjectMapper mapper = new ObjectMapper();
List<DeserializeJSON> agentsList = mapper.readValue(json,new TypeReference<List<DeserializeJSON>>() {});

我的反序列化

public class DeserializeJSON {
String Area;
Integer Quantity = 0;
boolean isSubArea = false;

public String getArea() {
    return Area;
}
public void setArea(String Area) {
    this.Area = Area;
}
public Integer getQuantity() {
    return Quantity;
}
public void setQuantity(Integer Quantity) {
    this.Quantity = Quantity;
}
public boolean isSubArea() {
    return isSubArea;
}
public void setSubArea(boolean isSubArea) {
    this.isSubArea = isSubArea;
}

}

但我收到错误

Unrecognized field "Area" (Class DeserializeJSON), not marked as ignorable at [Source: java.io.StringReader@2acf7a; line: 1, column: 11] (through reference chain: DeserializeJSON["Area"])

1 个答案:

答案 0 :(得分:2)

默认情况下,Jackson会在JavaBean naming conventions而不是字段中使用属性访问器。要使您的示例正常工作,您可以通过添加

来更改此示例
mapper.setVisibilityChecker(mapper.getVisibilityChecker().withFieldVisibility(Visibility.ANY));

查看VisibilityChecker上的其他方法,以正确自定义json映射。