简体   繁体   中英

How to create a Bean from JSON data?

This is the json structure I cannot control:

{
   "items":[
      {
         "rating":5.4,
         "count":10
      },
      {
         "rating":4.4,
         "count":13
      }
      //repeat...
    ]
}

I'm trying to generate an XSD from it, and then autogenerate a java class using xsd2java .

This is what I tried:

<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="list">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="items">
                <xs:complexType>
                  <xs:sequence>
                    <xs:element type="xs:int" name="rating"/>
                    <xs:element type="xs:int" name="count"/>
                  </xs:sequence>
                </xs:complexType>
    </xs:element>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
</xs:schema>

Which results in:

@XmlRootElement("list")
@XmlAccessorType(XmlAccessType.FIELD)
public class MyDTO {
    MyDTO.Items items;

    @XmlAccessorType(XmlAccessType.FIELD)
    public static class Items {
        private int rating;
        private int count;
    }
}

BUT: that is not correct: the items should be a List<Items> . What am I doing wrong?

You have to provide maxOccurs="unbounded" (or a non negative number). eg

<xs:complexType>
  <xs:sequence maxOccurs="unbounded">
      ....
  </xs:sequence>
</xs:complexType>

see http://www.w3schools.com/xml/el_sequence.asp for more information

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM