使用jackson xml mapper将xml反序列化为pojo [英] deserialize xml to pojo using jackson xml mapper
本文介绍了使用jackson xml mapper将xml反序列化为pojo的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我使用Jackson XML映射器将XML反序列化为POJO。 XML看起来像
I am using Jackson XML mapper to deserialize XML to POJO. The XML looks like
<person>
<agency>
<phone>111-111-1111</phone>
</agency>
</person>
我的班级看起来像
class Person
{
@JacksonXmlProperty(localName="agency", namespace="namespace")
private Agency agency;
//getter and setter
}
class Agency
{
@JacksonXmlElementWrapper(useWrapping = false)
@JacksonXmlProperty(localName="phone", namespace="namespace")
private List<AgencyPhone> phones;
//getter and setter
}
class AgencyPhone
{
private Phone phone;
//getter and setter
}
class Phone
{
private String number;
//getter and setter
}
我想设置电话号码在Phone类中编号。我无法更改XML或类的结构方式。我收到了无法构造 resolved.agency.AgencyPhone
错误的实例,我创建了一个AgencyPhone构造函数
I want to set the phone number to number in Phone class. I cannot change XML or the way the class has been structured. I am getting Cannot construct instance of resolved.agency.AgencyPhone
error and I created a AgencyPhone constructor
class AgencyPhone{
{
private Phone phone;
public AgencyPhone(Phone phone)
{
this.phone = phone;
}
}
但这不起作用。那么如何反序列化为嵌套实例。
But that did not work. So how to deserialize to nested instances.
推荐答案
您可以编写自己的自定义反序列化器来实现此目的。以下是让您入门的代码:
You can write your own custom deserialiser to achieve this. Here is the code to get you started:
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import java.io.IOException;
public class Test {
public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException {
XmlMapper mapper = new XmlMapper();
final SimpleModule module = new SimpleModule("configModule", com.fasterxml.jackson.core.Version.unknownVersion());
module.addDeserializer(Person.class, new DeSerializer());
mapper.registerModule(module);
// Person readValue = mapper.readValue(<xml source>);
}
}
class DeSerializer extends StdDeserializer<Person> {
protected DeSerializer() {
super(Person.class);
}
@Override
public Person deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
// use p.getText() and p.nextToken to navigate through the xml and construct Person object
return new Person();
}
}
这篇关于使用jackson xml mapper将xml反序列化为pojo的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文