gpt4 book ai didi

java - 将 JSON 映射到 java 类

转载 作者:行者123 更新时间:2023-12-01 15:02:38 25 4
gpt4 key购买 nike

我正在尝试使用 jackson 解析 JSON 字符串,如下所示:

{
"name":"John",
"Wrapper":{
"id":0
}
}

我试图避免为 Wrapper 创建另一个 Java 类,而只需将其映射到整数。我尝试使用 @XmlElementWrapper尽管文档指出:

This is primarily intended to be used to produce a wrapper XML element around collections.

但这不起作用。我收到以下异常:

Exception in thread "main" org.codehaus.jackson.map.JsonMappingException: Can not deserialize instance of java.lang.Integer out of START_OBJECT token
at [Source: java.io.StringReader@44eefb4; 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 提供了有限数量的结构转换注释( @JsonUnwrapped ,根值包装),但不适用于此用例。我认为这个特定用例实际上有一个功能请求(我认为是 @JsonWrapped )。

就其值(value)而言,Jackson JAXB 注释模块确实可以识别注释,但它不用于 JSON(它用于 XML 后端,但仅用于 Collection 和数组值属性)。

我只需添加一个简单的静态类 Wrapper ;或者,如果它是一个常见的习惯用法,则共享通用类 Wrapper<T> ,用于各种包装值。代码量会很简单,对象结构会与 JSON 数据结构一一匹配。

关于java - 将 JSON 映射到 java 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13426778/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com