2

I'm using EclipseLink's MOXy as the JAXB implementation in my RESTEasy project.MOXy's advanced functionality which has been brought by annotations like @XmlDiscriminatorNode & Value helped me a lot. Everything's working fine except one thing: JSON support. I'm using JettisonMappedContext of RESTEasy but unfortunately there're only instance variable fields belong to the abstract superclass in my JSON after marshalling.

@XmlRootElement
@XmlDiscriminatorNode("@type")
public abstract class Entity {

    public Entity(){}

    public Entity(String id){
        this.id = id;
    }

    private String id;

    @XmlElement
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
}

Subclass:

@XmlRootElement
@XmlDiscriminatorValue("photo")
public class Photo extends Entity{

    private String thumbnail;

    public Photo(){}

    public Photo(String id) {
        super(id);
    }

    public void setThumbnail(String thumbnail) {
        this.thumbnail = thumbnail;
    }

    @XmlElement(name="thumbnail")
    public String getThumbnail() {
        return thumbnail;
    }
}

XML after marshalling:

<object type="photo">
   <id>photoId423423</id>
   <thumbnail>http://dsadasadas.dsadas</thumbnail>
</object>

JSON after marshalling:

"object":{"id":"photoId423423"}

Is there any other way to achieve this?

Thank you.

barand
  • 174
  • 1
  • 9

1 Answers1

4

UPDATE 2

EclipseLink 2.4 has been released with MOXy's JSON binding:

UPDATE 1

Get a sneak peak of the native MOXy object-to-JSON binding being added in EclipseLink 2.4:


Ensure that you have included a file named jaxb.properties file with your model classes that contains the following entry:

javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory

Without this entry the reference implementation will be used, and the EclipseLink JAXB (MOXy) extensions will not appear in the resulting XML/JSON.


Using the @DescrimatorNode example from my blog, the XML produced would be:

<customer>
   <contactInfo classifier="address-classifier">
      <street>1 A Street</street>
   </contactInfo>
</customer>

When I marshal leveraging Jettison:

StringWriter strWriter = new StringWriter();
MappedNamespaceConvention con = new MappedNamespaceConvention();
AbstractXMLStreamWriter w = new MappedXMLStreamWriter(con, strWriter);
marshaller.marshal(customer, w);
System.out.println(strWriter.toString());

Then I get the following JSON:

{"customer":{"contactInfo":{"@classifier":"address-classifier","street":"1 A Street"}}}

For more information on JAXB and JSON see:

bdoughan
  • 147,609
  • 23
  • 300
  • 400