Home > Net >  Deserializing XML with nested fields to a single JavaObject
Deserializing XML with nested fields to a single JavaObject

Time:02-10

My goal is to convert the XML to JavaObject and have the JavaObject be able to handle one or more "Tasks".

I would also like to be able to convert the JavaObject to JSON as well.

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.

I have an XML file that follows this structure:

<Plan>
    <ID></ID>
    <Comment></Comment>
    <CreateTime></CreateTime>
    <Task>...</Task>
    <Task>...</Task>
    <Task>...</Task>
</Plan>

Each Task element is structured like so:

    <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. 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">

CodePudding user response:

  •  Tags:  
  • Related