Raj Bhatia
Raj Bhatia

Reputation: 1108

Map Java Object to @XmlElement Value

The LocationType Set coming null when I'm running JAXBxmlToJava. Can any body suggest how to map type component of xml to LocationType Object of Java. I have following 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>

And Following Code, 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();
        }
    }
}

Upvotes: 2

Views: 1335

Answers (1)

Glorfindel
Glorfindel

Reputation: 22651

You'll need @XmlValue to map a text node (e.g. 'neighborhood') to a field in a custom class.

When I tested your code, the Set<LocationType> wasn't null - there were two LocationTypes in it, but their type field was null. I'm not sure if that is what you meant in your question.

When I changed the LocationType class to

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

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

it worked.

Upvotes: 1

Related Questions