从JSON输出泽西moxy中删除"type"

Rob*_*bAu 9 java json jersey marshalling moxy

如何type从我拥有的JSON输出中删除.我有一个包含REST服务输出的类/ bean.我正在使用jersey-media-moxy转换.

服务

@Resource
public interface MyBeanResource
{
    @GET
    @Path("/example")
    @Produces( MediaType.APPLICATION_JSON )
    public Bean getBean();
}
Run Code Online (Sandbox Code Playgroud)

@XmlRootElement
class Bean
{
   String a;
}  
Run Code Online (Sandbox Code Playgroud)

我想添加一些功能(用于使用构造函数初始化bean)

class BeanImpl extends Bean
{
    BeanImpl(OtherClass c)
    {
        a = c.toString()
    }
}
Run Code Online (Sandbox Code Playgroud)

输出的JSON是:

{type:"beanImpl", a:"somevalue"}

我不想要type我的JSON.我该如何配置?

小智 15

当我扩展一个类并生成JSON时,我得到了同样的错误 - 但仅限于顶级(根)类.作为一种变通方法,我诠释我的子类@XmlType(name=""),防止产生type属性出现在我的JSON.

Blaise,我不确定为什么会这样.有什么想法吗?

  • 使用name属性,您可能会覆盖将在type属性中写入的内容.由于您将其定义为空,因此Jersey会完全跳过该属性. (2认同)

Ste*_*han 1

您可以构建自定义消息正文编写器。

@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"));
    }
}
Run Code Online (Sandbox Code Playgroud)