Mapping xml to Java Objects - Null Pointer in Class

0

I'm trying to map an xml to Java classes. It turns out that I get an xml input, and I need to break it down in classes.

INPUT XML:

<empleado>
  <nombre>juan</nombre>
  <segundo_nombre>pablo</segundo_nombre>
  <apellido>perez</apellido>
  <dni>9999</dni>
  <calle>San martin</calle>
  <numero_calle>123</numero_calle>
  <piso>4r</piso>
</empleado>

I need you to tag them and be in another class. I mapped it in the following way:

EMPLOYEE CLASS:

@XmlRootElement(name = "empleado")
@XmlAccessorType(XmlAccessType.NONE)
public class Empleado implements Serializable {
    @XmlElement(name = "nombre", required = true)
    private String nombre;
    @XmlElement(name = "segundo_nombre", required = true)
    private String segundo_nombre;
    @XmlElement(name = "dni", required = true)
    private String dni;
    private Direccion direccion = new Direccion();

CLASS ADDRESS:

@XmlRootElement(name = "empleado")
@XmlAccessorType(XmlAccessType.FIELD)
public class Direccion implements Serializable {
    private String calle;
    private String numero_calle;
    private String piso;

Both with their setters and getters.

When doing the Unmarshall

    public static void main(String[] args) throws Exception {
    try {
        //getting the xml file to read
        File file = new File("\Empleado.xml");
        System.out.println("{} processing fileName='{}'" + file);

        //creating the JAXB context
        JAXBContext jContext = JAXBContext.newInstance(Direccion.class, Empleado.class);
        //creating the unmarshall object
        unmarshaller = jContext.createUnmarshaller();
        //calling the unmarshall method
        Empleado emp = (Empleado) unmarshaller.unmarshal(file);
        System.out.println(emp.toString());
    } catch (Exception e) {
        e.printStackTrace();
    }
}

Return me:

> Empleado{nombre=juan, segundo_nombre=pablo, dni=9999,
> direccion=Direccion{calle=null, numero_calle=null, piso=null}}

I'm not taking the address class data. Anyone know what might be happening? or how else can you represent this?

Thank you very much !!

    
asked by Maria Laura 23.07.2018 в 19:17
source

1 answer

1

It seems to me that the annotation @XmlElement goes in the get methods and not in the attributes, I have an example so if it works:

@XmlElement    //nombre del tag xml
public String getPuesto() {
    return puesto;
}
    
answered by 23.07.2018 / 19:25
source