当我运行JAXBxmlToJava时,LocationType设置为null。任何人都可以建议如何将xml的类型组件映射到Java的LocationType对象。
我有以下arc-response.xml:

<address_component>
   <long_name>BMC Colony</long_name>
   <short_name>BMC Colony</short_name>
   <type>neighborhood</type>
   <type>political</type>
  </address_component>


及以下代码,AddressComponent:-

@XmlRootElement(name = "address_component")
public class AddressComponent {

    @XmlElement(name = "long_name")
    private String longName;
    @XmlElement(name = "short_name")
    private String shortName;
    @XmlElement(name = "type")
    private Set<LocationType> locationTypeSet;
    //Setter Getter
}


LocationType:-

@XmlRootElement(name="type")
public class LocationType {

    private Integer locationTypeId;
    @XmlElement(name = "type")
    private String type;
    private String status;
    //Setter Getter
}


JAXBxmlToJava.java:-

    public class JAXBxmlToJava {
    public static void main(String[] args) {
        try {
            File file = new File("arc-response.xml");
            JAXBContext jaxbContext = JAXBContext.newInstance(AddressComponent.class);

            Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
            AddressComponent geoResponse = (AddressComponent) jaxbUnmarshaller.unmarshal(file);
            System.out.println(geoResponse);
        } catch (JAXBException e) {
            e.printStackTrace();
        }
    }
}

最佳答案

您需要@XmlValue将文本节点(例如,“ neighborhood”)映射到自定义类中的字段。

当我测试您的代码时,Set<LocationType>不是null-其中有两个LocationType,但是它们的type字段是null。我不确定这是否代表您的问题。

当我将LocationType类更改为

@XmlRootElement(name = "type")
public class LocationType {

    private Integer locationTypeId;
    @XmlValue
    private String type;
    private String status;
    // Setter Getter
}


有效。

07-24 19:14