我需要使用jackson-dataformat-xml将一些XML文件反序列化为常规java对象。所以我在做:
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
XmlMapper mapper = new XmlMapper();
return mapper.readValue(xmlString, Certificate.class);
xmlString 有外观:
<?xml version="1.0" encoding="UTF-8"?>
<doc>
<r key="0">
<ATT_SEARCH DM="dm1" DS="ds1" DocType="1"/>
<ATT_SEARCH DM="dm2" DS="ds2" DocType="2"/>
</r>
</doc>
班级证书:
package ua.max;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import java.util.List;
@JacksonXmlRootElement(localName = "doc")
@XmlAccessorType(XmlAccessType.FIELD)
public class Certificate {
@JacksonXmlProperty(localName = "r")
private R r;
public R getR() {
return r;
}
public void setR(R r) {
this.r = r;
}
public class R {
@JacksonXmlProperty(localName = "ATT_SEARCH")
@JacksonXmlElementWrapper(useWrapping = false)
private List<AttSearch> attSearch;
public List<AttSearch> getAttSearch() {
return attSearch;
}
public void setAttSearch(List<AttSearch> attSearch) {
this.attSearch = attSearch;
}
@JacksonXmlProperty(isAttribute = true, localName = "key")
private String key;
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public class AttSearch {
@JacksonXmlProperty(isAttribute = true, localName = "DM")
private String dm;
@JacksonXmlProperty(isAttribute = true, localName = "DS")
private String ds;
@JacksonXmlProperty(isAttribute = true, localName = "DocType")
private String docType;
public String getDm() {
return dm;
}
public void setDm(String dm) {
this.dm = dm;
}
public String getDs() {
return ds;
}
public void setDs(String ds) {
this.ds = ds;
}
public String getDocType() {
return docType;
}
public void setDocType(String docType) {
this.docType = docType;
}
}
}
}
在尝试去实现XML之后,我得到了例外:
“找不到类型[simple type,class ua.max.Certificate $ R]的合适构造函数:无法从JSON对象实例化”
我的尝试:
1.如果我为我的内部类添加修饰符“static”它正在工作,我得到java对象,但除了2个对象的列表“ATT-SEARCH”我得到的第一个是null
2.添加不同的构造函数没有任何影响
答案 0 :(得分:3)
R
和AttSearch
应该是静态的:
public static class R {
// other stuff
public static class AttSearch {
// other stuff
否则编译器使用外部类引用作为参数创建默认构造函数,因此fastxml无法找到没有参数的构造函数并创建pojo。