我試圖解析與傑克遜JSON字符串,看起來像:映射一個JSON Java類
{
"name":"John",
"Wrapper":{
"id":0
}
}
我試圖防止不得不做出另一個Java類Wrapper
,並簡單地將其映射到一個整數代替。我試着用@XmlElementWrapper
即使文檔指出:
這主要是爲了用於生產周圍集合包裝XML元素 。
但這不起作用。我得到以下異常:
Exception in thread "main" org.codehaus.jackson.map.JsonMappingException: Can not deserialize instance of java.lang.Integer out of START_OBJECT token
at [Source: [email protected]; line: 1, column: 15] (through reference chain: Test["Wrapper"])
at org.codehaus.jackson.map.JsonMappingException.from(JsonMappingException.java:163)
at org.codehaus.jackson.map.deser.StdDeserializationContext.mappingException(StdDeserializationContext.java:219)
at org.codehaus.jackson.map.deser.std.StdDeserializer._parseInteger(StdDeserializer.java:305)
at org.codehaus.jackson.map.deser.std.StdDeserializer$IntegerDeserializer.deserialize(StdDeserializer.java:795)
at org.codehaus.jackson.map.deser.std.StdDeserializer$IntegerDeserializer.deserialize(StdDeserializer.java:782)
at org.codehaus.jackson.map.deser.SettableBeanProperty.deserialize(SettableBeanProperty.java:299)
at org.codehaus.jackson.map.deser.SettableBeanProperty$FieldProperty.deserializeAndSet(SettableBeanProperty.java:579)
at org.codehaus.jackson.map.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:697)
at org.codehaus.jackson.map.deser.BeanDeserializer.deserialize(BeanDeserializer.java:580)
at org.codehaus.jackson.map.ObjectMapper._readMapAndClose(ObjectMapper.java:2723)
at org.codehaus.jackson.map.ObjectMapper.readValue(ObjectMapper.java:1854)
at Test.main(Test.java:37)
這裏是一個可運行的例子:
@XmlAccessorType(XmlAccessType.FIELD)
public class Test {
public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException {
String json =
"{" +
"\"name\":\"John\","+
"\"Wrapper\":{"+
" \"id\":0}"+
"}";
ObjectMapper mapper = new ObjectMapper();
mapper.setAnnotationIntrospector(new JaxbAnnotationIntrospector());
mapper.setSerializationInclusion(Inclusion.NON_NULL);
Test test = mapper.readValue(json, Test.class);
System.out.println(test.toString());
}
@XmlElement(name="name")
private String name;
@XmlElementWrapper(name="Wrapper")
@XmlElement(name="id")
private Integer wrapperId;
@Override
public String toString() {
return "Test [name=" + name + ", wrapperId=" + wrapperId + "]";
}
}
如果您對除Jackson以外的JSON綁定提供程序感興趣,下面是使用EclipseLink MOXy的「@ XmlPath」註釋演示如何支持您的用例的鏈接:http://blog.bdoughan.com/2011/08/ binding-to-json-xml-geocode-example.html –