Remove "type" from JSON output jersey moxy Remove "type" from JSON output jersey moxy json json

Remove "type" from JSON output jersey moxy


I get the same error when I extend a class and generate JSON -- but only for a top-level (root) class. As a workaround, I annotate my subclass with @XmlType(name=""), which prevents the generated type property from appearing in my JSON.

Blaise, I'm not sure why this works. Any thoughts?


MOXy will add a type indicator to differentiate between the different subtypes. This however will only happen if MOXy is aware of the subtypes (it isn't by default).

Demo Code

Demo

Below is the equivalent code that Jersey will call on MOXy.

import org.eclipse.persistence.jaxb.rs.MOXyJsonProvider;public class Demo {    public static void main(String[] args) throws Exception {        MOXyJsonProvider mjp = new MOXyJsonProvider();        BeanImpl beanImpl = new BeanImpl(new OtherClass());        mjp.writeTo(beanImpl, Bean.class, Bean.class, null, null, null, System.out);    }}

Output

{}

Possible Problem?

Do you potentially have an @XmlSeeAlso annotation on your real Bean class?

import javax.xml.bind.annotation.*;@XmlRootElement@XmlSeeAlso(BeanImpl.class)class Bean{   String a;}  

Then the output will be (assuming BeanImpl also has a no-arg constructor):

{"type":"beanImpl"}


You can build a custom message body writer .

@Provider@Produces({   MediaType.APPLICATION_JSON})public class BeanBodyWriter implements MessageBodyWriter<Bean> {    @Override    public long getSize(Bean t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {        // Called before isWriteable by Jersey. Return -1 if you don't the size yet.         return -1;    }    @Override    public boolean isWriteable(Class<?> clazz, Type genericType, Annotation[] annotations, MediaType mediaType) {        // Check that the passed class by Jersey can be handled by our message body writer        return Bean.class.isAssignableFrom(clazz);    }    @Override    public void writeTo(Bean t, Class<?> clazz, Type genericType, Annotation[] annotations, MediaType mediaType,            MultivaluedMap<String, Object> httpHeaders, OutputStream out) throws IOException, WebApplicationException {        // Call your favorite JSON library to generate the JSON code and remove the unwanted fields...        String json = "...";        out.write(json.getBytes("UTF-8"));    }}