映射< String,Object>的jackson xmlmapper,对特定标签做出反应 [英] jackson xmlmapper for map <String, Object>, react for specific tag
问题描述
我有这个xml结构:
<Result>
<ReferenceMin>4</ReferenceMin>
<ReferenceMax>5.65</ReferenceMax>
<PrecedingValue>3.25</PrecedingValue>
<PrecedingDate><Date year="2017" month="04" day="21"/></PrecedingDate>
</Result>
此xml来自无法控制的第三方服务,它可以包含新字段,或者现有字段可以消失,因此我无法为对象定义严格的结构.如我所见,除PrecedingDate外,所有字段都可以解析为字符串".
This xml come from 3-rd party service which can not be controlled, and it can contain new fields, or existing fields can disappear, so I can't define strict structure for object. As I can see, all fields can be parsed as "String" except PrecedingDate.
是否可以通过我的Cyustom策略将Jackson xmlMapper与PrecedingDate或Date字段一起使用?当前,它创建具有以下结构的对象:
Is it possible to teach jackson xmlMapper work with PrecedingDate or Date field by my cyustom strategy? Currently it create objects with this structure:
{PrecedingDate: Date: {year: 2017, month: 04, day: 21}}
我想获取java日期或即时信息或类似的信息.
I want to get java date or instant or something similar.
推荐答案
您可以实现自定义反序列化程序或使用JsonAnySetter
批注.您可以在下面找到如何使用注释:
You can implement custom deserialiser or use JsonAnySetter
annotation. How to use annotation you can find below:
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import java.io.File;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.Map;
public class XmlMapperApp {
public static void main(String[] args) throws Exception {
File xmlFile = new File("./resource/test.xml").getAbsoluteFile();
XmlMapper xmlMapper = new XmlMapper();
System.out.println(xmlMapper.readValue(xmlFile, Result.class));
}
}
class Result {
private Map<String, String> entries = new HashMap<>();
private LocalDate precedingDate;
public Map<String, String> getEntries() {
return entries;
}
public LocalDate getPrecedingDate() {
return precedingDate;
}
@JsonAnySetter
public void setEntry(String key, Object value) {
if ("PrecedingDate".equals(key)) {
Map<String, String> date = (Map<String, String>)((Map) value).get("Date");
precedingDate = LocalDate.of(
Integer.parseInt(date.get("year")),
Integer.parseInt(date.get("month")),
Integer.parseInt(date.get("day")));
} else {
entries.put(key, value.toString());
}
}
@Override
public String toString() {
return "Result{" +
"entries=" + entries +
", precedingDate=" + precedingDate +
'}';
}
}
上面的代码显示:
Result{entries={ReferenceMin=4, PrecedingValue=3.25, ReferenceMax=5.65}, precedingDate=2017-04-21}
这篇关于映射< String,Object>的jackson xmlmapper,对特定标签做出反应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!