简体   繁体   English

如何从JSON数据创建Bean?

[英]How to create a Bean from JSON data?

This is the json structure I cannot control: 这是我无法控制的json结构:

{
   "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 . 我试图从中生成一个XSD,然后使用xsd2java自动生成一个Java类。

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> . 但是:这是不正确的:这些items应该是List<Items> What am I doing wrong? 我究竟做错了什么?

You have to provide maxOccurs="unbounded" (or a non negative number). 您必须提供maxOccurs =“ unbounded”(或非负数)。 eg 例如

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

see http://www.w3schools.com/xml/el_sequence.asp for more information 有关更多信息,请参见http://www.w3schools.com/xml/el_sequence.asp

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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