3

I am trying to marshal an Object with an Object field (which can be numerous types of classes). I will then send the generated XML using sockets. My code is as follows;

My class to which I would like to marshall

public class Message {

    private String metadata;

    private Object payload;


    public Message(String metadata,Object payload)
    {
        this.metadata=metadata;
        this.payload=payload;
    }

    public Message() {

    }

    public String getMetadata() {
        return metadata;
    }

    public void setMetadata(String metadata) {
        this.metadata = metadata;
    }

    public Object getPayload() {
        return payload;
    }

    public void setPayload(Object payload) {
        this.payload = payload;
    }

}

Snippet of how I attempt to marshall it.

 private Message sendData; 
    ...
    JAXBContext jc = JAXBContext.newInstance(sendData.getClass());      
    Marshaller m = jc.createMarshaller();
    m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    JAXBElement<Message> rootElement = new JAXBElement<Message>(
                            new QName(sendData.getClass().getSimpleName()), dataClass,
                            sendData);
                    m.marshal(rootElement, stringWriter);

When I first attempted it using an ArrayLlist, I got the following error:

javax.xml.bind.MarshalException - with linked exception: [com.sun.istack.internal.SAXException2: class java.util.ArrayList nor any of its super class is known to this context. javax.xml.bind.JAXBException: class java.util.ArrayList nor any of its super class is known to this context.]

Now I understand that it doesn't know how to parse it. Having looked and implemented an answer to this question, where you wrap the Object to a JAXBElement, I still got the above error.

Any Idea's how I can get around this? Much appreciated!

Community
  • 1
  • 1
Stu Whyte
  • 758
  • 5
  • 19

1 Answers1

5

A JAXB (JSR-222) implementation will expect a property of type Object to be a singular item and not a collection. This is why you are getting the exception.

You could change the payload property to be type List<Object>. Then singular values could be treated as a size 1 List.

bdoughan
  • 147,609
  • 23
  • 300
  • 400
  • My implementation of it allowed lists of some Objects - but not others. Ended up using XStream instead! But thanks for your help! – Stu Whyte Jul 16 '13 at 15:56
  • 1
    @ Stu Whyte: Can you please provide your solution using XStream. – Rahul Oct 07 '14 at 11:39