Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid creation of object wrapper type/value in MOXy (JAXB+JSON)

Tags:

java

json

jaxb

moxy

I'm using MOXy 2.6 (JAXB+JSON).

I want ObjectElement and StringElement to be marshalled the same way, but MOXy creates wrapper object when fields are typed as Object.

ObjectElement.java

public class ObjectElement {
    public Object testVar = "testValue";
}

StringElement.java

public class StringElement {
    public String testVar = "testValue";
}

Demo.java

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;

import org.eclipse.persistence.jaxb.JAXBContextFactory;
import org.eclipse.persistence.jaxb.MarshallerProperties;
import org.eclipse.persistence.oxm.MediaType;

public class Demo {

    public static void main(String[] args) throws Exception {
        JAXBContext jc = JAXBContextFactory.createContext(new Class[] { ObjectElement.class, StringElement.class }, null);
        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(MarshallerProperties.MEDIA_TYPE, MediaType.APPLICATION_JSON);

        System.out.println("ObjectElement:");
        ObjectElement objectElement = new ObjectElement();
        marshaller.marshal(objectElement, System.out);
        System.out.println();

        System.out.println("StringElement:");
        StringElement stringElement = new StringElement();
        marshaller.marshal(stringElement, System.out);
        System.out.println();
    }

}

When launching Demo.java, here's the output ...

ObjectElement:
{"testVar":{"type":"string","value":"testValue"}}
StringElement:
{"testVar":"testValue"}

How to configure MOXy/JaxB to make ObjectElement render as StringElement object ? How to avoid the creation of object wrapper with "type" and "value" properties ?

like image 937
Toilal Avatar asked Jun 04 '15 14:06

Toilal


1 Answers

you can use the Annotation javax.xml.bind.annotation.XmlAttribute. This will render ObjectElement and StringElement to the same output.

See the following example:

import javax.xml.bind.annotation.XmlAttribute;

public class ObjectElement {
    @XmlAttribute
    public Object testVar = "testValue";
}

I've used the following test class to verify the correct behaviour.

EDIT after the question was updated:

Yes it's possible. Instead of using XmlAttribute like before, I switched to javax.xml.bind.annotation.XmlElement in combination with a type attribute.

The class is now declared as:

public class ObjectElement {
  @XmlElement(type = String.class)
  public Object testVar = "testValue";
}
like image 119
Andreas Aumayr Avatar answered Sep 28 '22 09:09

Andreas Aumayr