Michael Munsey
Michael Munsey

Reputation: 3870

JAXB not marshalling nested objects with Jersey

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;

public class App {
    public static void main(String[] args){
        Client client = Client.create();
        WebResource webResource = client.resource("https://mywebsite.com/getDevices");
        ClientResponse response = webResource.accept("application/xml").get(
                ClientResponse.class);
        System.out.println(response.getEntity(Devices.class));
    }
}

Devices.java

import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(namespace="myNamespace", propOrder = {"deviceList"})
@XmlRootElement(name = "Entries", namespace="myNamespace")
public class Devices {

    @XmlElement(name = "Entry", namespace="myNamespace")
    protected List<Devices.Device> deviceList;

    public List<Devices.Device> getEntry() {
        if (deviceList == null) {
            deviceList = new ArrayList<Devices.Device>();
        }
        return this.deviceList;
    }

    @Override
    public String toString() {
        return deviceList.toString();
    }

    @XmlAccessorType(XmlAccessType.FIELD)
    @XmlType(propOrder = {"devicename"})
    public static class Device {
        String devicename;

        public String getDevicename() {
            return devicename;
        }

        public void setDevicename(String value) {
            this.devicename = value;
        }

        @Override
        public String toString() {
            return devicename;
        }
    }
}

Sample XML returned from Web Service

<Entries xmlns="myNamespace">
  <Entry><devicename xmlns="myNamespace">Device1</devicename></Entry>
  <Entry><devicename xmlns="myNamespace">Device2</devicename></Entry>
</Entries>

It seems to correctly pull in the data, but returns null for each devicename.

Upvotes: 1

Views: 570

Answers (1)

bdoughan
bdoughan

Reputation: 149017

Instead of how you are currently mapping your namespace qualification you could use the package level @XmlSchema annotation on a class called package-info that looks like the following:

package-info.java

@XmlSchema(
    namespace = "myNamespace",
    elementFormDefault = XmlNsForm.QUALIFIED)
package your.pkg;

import javax.xml.bind.annotation.XmlNsForm;
import javax.xml.bind.annotation.XmlSchema;

For More Information

Upvotes: 1

Related Questions