问题
I have this xml structure:
<Result>
<ReferenceMin>4</ReferenceMin>
<ReferenceMax>5.65</ReferenceMax>
<PrecedingValue>3.25</PrecedingValue>
<PrecedingDate><Date year="2017" month="04" day="21"/></PrecedingDate>
</Result>
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.
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}}
I want to get java date or instant or something similar.
回答1:
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 +
'}';
}
}
Above code prints:
Result{entries={ReferenceMin=4, PrecedingValue=3.25, ReferenceMax=5.65}, precedingDate=2017-04-21}
来源:https://stackoverflow.com/questions/57461455/jackson-xmlmapper-for-map-string-object-react-for-specific-tag