使用Jackson序列化为 XML时,我似乎遇到了问题.我的代码如下: 测试容器 package com.test;import java.util.ArrayList;import com.fasterxml.jackson.annotation.JsonProperty;public class TestContainer { private String testCo
测试容器
package com.test;
import java.util.ArrayList;
import com.fasterxml.jackson.annotation.JsonProperty;
public class TestContainer {
private String testContainerID;
private String testContainerMessage;
private ArrayList<TestChild> testContainerChildren;
@JsonProperty("TestContainerID")
public String getTestContainerID() {
return testContainerID;
}
@JsonProperty("TestContainerID")
public void setTestContainerID(String testContainerID) {
this.testContainerID = testContainerID;
}
@JsonProperty("TestContainerMessage")
public String getTestContainerMessage() {
return testContainerMessage;
}
@JsonProperty("TestContainerMessage")
public void setTestContainerMessage(String testContainerMessage) {
this.testContainerMessage = testContainerMessage;
}
@JsonProperty("TestContainerChildren")
public ArrayList<TestChild> getTestContainerChildren() {
return testContainerChildren;
}
@JsonProperty("TestContainerChildren")
public void setTestContainerChildren(ArrayList<TestChild> testContainerChildren) {
this.testContainerChildren = testContainerChildren;
}
}
TESTCHILD
package com.test;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonRootName;
@JsonRootName(value="TestChild")
public class TestChild {
private String testChildID;
private String testChildMessage;
@JsonProperty("TestChildID")
public String getTestChildID() {
return testChildID;
}
@JsonProperty("TestChildID")
public void setTestChildID(String testChildID) {
this.testChildID = testChildID;
}
@JsonProperty("TestChildMessage")
public String getTestChildMessage() {
return testChildMessage;
}
@JsonProperty("TestChildMessage")
public void setTestChildMessage(String testChildMessage) {
this.testChildMessage = testChildMessage;
}
}
使用
>序列化:
XmlMapper xm = new XmlMapper();
TestContainer tc = xm.readValue(sb.toString(),TestContainer.class);
>反序列化:
的System.out.println(xm.writeValueAsString(TC));
tc = xm.readValue(sb.toString(),TestContainer.class);
我正在做的是从类路径上的文件夹加载XML文件,并将文件的内容放入StringBuffer.问题是为对象集合生成的XML.在编写XML时,我需要以下内容:
<TestContainerChildren><TestChild><...(Element Details)...></TestChild></TestContainerChildren>
但我得到了:
<TestContainerChildren><TestContainerChildren><...(Element Details)...><TestContainerChildren></TestContainerChildren>
我不确定我在这里缺少什么.我对序列化/反序列化的JSON部分没有问题,只有XML.我已经尝试使用Jackson和JAXB注释来关闭包装,我尝试使用以下注释:
> @JsonRootName
> @JsonProperty
> @JacksonXmlElementWrapper
> @JacksonElement
> @XmlElementWrapper
> @XmlElement
我很确定这对我来说是愚蠢的,但任何帮助都会非常感激.
我通过在变量声明之上使用以下注释来实现此功能:> @JacksonXmlElementWrapper(localName =“[insert collection name]”)
> @JacksonXmlProperty(localName =“[插入集合元素名称]”)
这是一个简单的RTFM案例,因为它记录了here.
