我收到以下错误消息,我有Status类但它没有被识别.我不知道如何继续,也无法在线找到答案.
错误
org.springframework.http.converter.HttpMessageNotReadableException: Could
not read JSON: Unrecognized field "Status" (class
com.myproject.ticket.EventsResponse), not marked as ignorable (3 known
properties: "events", "status", "page"])
....
Caused by:
com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException:
Unrecognized field "Status" (class com.myproject.ticket.EventsResponse),
not marked as ignorable (3 known properties: "events", "status", "page"])
Run Code Online (Sandbox Code Playgroud)
EventsResponse
@XmlRootElement(name = "EventsResponse")
@XmlAccessorType(XmlAccessType.FIELD)
public class EventsResponse {
@XmlElement(name = "Status")
private Status status;
@XmlElement(name = "Paging")
private Page page;
@XmlElementWrapper(name="Events")
@XmlElement(name = "Event")
private List<Event> events;
.....
Run Code Online (Sandbox Code Playgroud)
状态
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Status {
@XmlElement(name = "Version")
private double version;
@XmlElement(name = "TimeStampUtc")
private Date timeStampUtc;
@XmlElement(name = "Code")
private int code;
@XmlElement(name = "Message")
private String message;
@XmlElement(name = "Details")
private String details;
Run Code Online (Sandbox Code Playgroud)
响应
<EventsResponse xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<Status>
<Version>2.0</Version>
<TimeStampUtc>2016-06-11T09:32:21</TimeStampUtc>
<Code>0</Code>
<Message>Success</Message>
<Details />
</Status>
<Paging>
<PageNumber>1</PageNumber>
<PageSize>50</PageSize>
<PageResultCount>15</PageResultCount>
<TotalResultCount>15</TotalResultCount>
<TotalPageCount>1</TotalPageCount>
</Paging>
<Events>
<Event>
Run Code Online (Sandbox Code Playgroud)
我添加了以下状态,但我仍然收到相同的错误.
@XmlElement(name = "Status")
@JacksonXmlProperty(localName = "Status")
private Status status;
Run Code Online (Sandbox Code Playgroud)
小智 1
假设您使用 Jackson 来反序列化 XML 对象,您有两个选择。最简单的方法是使用 Jackson 自己的 XML 注释来代替 JAXB 注释,或者与 JAXB@XmlElement
注释一起使用。例如:
@XmlElement(name = "Status")
@JacksonXmlProperty(localName = "Status")
private Status status;
Run Code Online (Sandbox Code Playgroud)
(@XmlElement
注释位于jackson-dataformat-xml
Maven 中的包中 - 该版本应与您的其他 Jackson 包版本相匹配。)
另一种方法是注册 AnnotationIntrospector 作为反序列化链的一部分 - 即。(来自单元测试):
XmlMapper mapper = new XmlMapper();
AnnotationIntrospector aiJaxb = new JaxbAnnotationIntrospector(TypeFactory.defaultInstance());
mapper.setAnnotationIntrospector(aiJaxb);
// EVENTS_RESPONSE is the incoming XML
EventsResponse response = mapper.readValue(EVENTS_RESPONSE, EventsResponse.class);
Run Code Online (Sandbox Code Playgroud)
这会识别@XmlElement
注释。例如,如果您需要将其作为 Spring 配置的一部分包含在内,则此答案中有更多详细信息。
(为了使用该类JaxbAnnotationIntrospector
,您需要jackson-module-jaxb-annotation
Maven 中的模块。)