[英]Deserializing XML with nested fields to a single JavaObject
My goal is to convert the XML to JavaObject and have the JavaObject be able to handle one or more "Tasks".我的目标是将 XML 转换为 JavaObject 并让 JavaObject 能够处理一个或多个“任务”。
I would also like to be able to convert the JavaObject to JSON as well.我还希望能够将 JavaObject 转换为 JSON。
How can this be done?如何才能做到这一点? At it's current state, I am able to convert if only one task exists, anymore results in an error.
当前为 state,如果只存在一个任务,我可以转换,但会导致错误。
I have an XML file that follows this structure:我有一个遵循以下结构的 XML 文件:
<Plan>
<ID></ID>
<Comment></Comment>
<CreateTime></CreateTime>
<Task>...</Task>
<Task>...</Task>
<Task>...</Task>
</Plan>
Each Task element is structured like so:每个 Task 元素的结构如下:
<Task>
<Type></Type>
<Time></Time>
<Target>
<Code></Code>
<TargetId></TargetId>
<Content>
<Stuff1></Stuff1>
<Stuff2></Stuff2>
<Stuff3></Stuff3>
</Content>
</Target>
</Task>
I am able to deserialize the XML when there is only one Task involved.当只涉及一个任务时,我能够反序列化 XML。 Anymore gives me errors.
再给我错误。
My Classes (simplified) are as follows:我的课程(简化)如下:
@Root(name = "Plan")
public class Plan{
@Element(name = "ID")
private String id;
@Element(name = "Comment")
private String comment;
@Element(name = "CreateTime")
private String createTime;
@Element(name = "Task")
private Task task;
}
@Root(name = "Task")
public class Task{
@Element(name = "Type")
private String type;
@Element(name = "Time")
private String time;
@Element(name = "Target")
private Target target;
}
@Root(name = "Target")
public class Target{
@Element(name = "Code")
private String code;
@Element(name = "TargetId")
private String targetId;
@Element(name = "Content")
private Content content;
}
@Root(name = "Content")
public class Content{
@Element(name = "Stuff1")
private String stuff1;
@Element(name = "Stuff2")
private String stuff2;
@Element(name = "Stuff3")
private String stuff3;
}
In the schema file, I set this but doesn't seem to work:在架构文件中,我设置了这个但似乎不起作用:
<xs:element name="Task" type="Task" minOccurs="1" maxOccurs="unbounded">
At it's current state, I am able to convert if only one task exists, anymore results in an error.
当前为 state,如果只存在一个任务,我可以转换,但会导致错误。
This happens because your element annotation interprets the task tag as a property, so if there is more than one it raises an error.发生这种情况是因为您的元素注释将任务标记解释为一个属性,因此如果有多个标记,则会引发错误。 To avoid this behaviour you can use the
JacksonXmlElementWrapper
annotation you can apply to your task list:为避免此行为,您可以使用可应用于任务列表的
JacksonXmlElementWrapper
注释:
public class Plan {
@JacksonXmlProperty(localName = "Task")
@JacksonXmlElementWrapper(useWrapping = false)
List<Task> tasks;
}
public class Task {}
This above is a starting basic example you can use to define more complicated xmls.以上是一个入门的基本示例,您可以使用它来定义更复杂的 xml。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.