1
我有一个服务,它返回JSON和XML格式的对象。杰克逊xml和json根元素
http://localhost:8091/apiN/xml/2
XML结果
<restObjectList>
<restObjectList>
<restObjectList>
<timestamp>2017-06-19 17:01:01</timestamp>
<title>Rest object</title>
<fullText>This is the full text. ID: 1</fullText>
<id>1</id>
<value>0.1412789210135622</value>
</restObjectList>
<restObjectList>
<timestamp>2017-06-19 17:01:01</timestamp>
<title>Rest object</title>
<fullText>This is the full text. ID: 2</fullText>
<id>2</id>
<value>0.9886539664938628</value>
</restObjectList>
</restObjectList>
</restObjectList>
http://localhost:8091/apiN/2
JSON结果
{
"restObjectList": [
{
"timestamp": "2017-06-19 17:01:01",
"title": "Rest object",
"fullText": "This is the full text. ID: 1",
"id": 1,
"value": 0.1412789210135622
},
{
"timestamp": "2017-06-19 17:01:01",
"title": "Rest object",
"fullText": "This is the full text. ID: 2",
"id": 2,
"value": 0.9886539664938628
}
]
}
结果我想收到
XML
<restObjectList>
<restObject>
<timestamp>2017-06-19 17:01:01</timestamp>
<title>Rest object</title>
<fullText>This is the full text. ID: 1</fullText>
<id>1</id>
<value>0.1412789210135622</value>
</restObject>
<restObject>
<timestamp>2017-06-19 17:01:01</timestamp>
<title>Rest object</title>
<fullText>This is the full text. ID: 2</fullText>
<id>2</id>
<value>0.9886539664938628</value>
</restObject>
</restObjectList>
JSON
{
"restObjectList": [{
"restObject": {
"timestamp": "2017-06-19 17:01:01",
"title": "Rest object",
"fullText": "This is the full text. ID: 1",
"id": 1,
"value": 0.1412789210135622
}
}, {
"restObject": {
"timestamp": "2017-06-19 17:01:01",
"title": "Rest object",
"fullText": "This is the full text. ID: 2",
"id": 2,
"value": 0.9886539664938628
}
}]
}
如何包装restObject
对JSON和XML和XML解决数据restObjectList
因为这个标签在不同层次重复。
我的代码
RestObject
@JsonRootName(value = "restObject")
@XmlRootElement(name = "restObject")
public class RestObject implements Serializable {
private LocalDateTime timestamp;
private String title;
private String fullText;
private Long id;
private Double value;
//Getters, setters
}
RestObjectList
@JsonRootName(value = "restObjectList")
@XmlSeeAlso({RestObject.class})
public class RestObjectList {
private List<RestObject> restObjectList;
//Getter and setter
}
JacksonConfig
@Configuration
public class JacksonConfig {
@Bean
public ObjectMapper objectMapper(Jackson2ObjectMapperBuilder builder) {
ObjectMapper objectMapper = builder.createXmlMapper(true).build();
objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);//Use custom date-time format.
objectMapper.configure(SerializationFeature.WRAP_ROOT_VALUE, false);
objectMapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, false);
return objectMapper;
}
@Bean
public ObjectMapper objectMapper() {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.enable(SerializationFeature.WRAP_ROOT_VALUE);
objectMapper.enable(DeserializationFeature.UNWRAP_ROOT_VALUE);
return objectMapper;
}
}