java - 未调用 Long 数据类型的自定义 MessageBodyWriter

标签 java rest cxf

我有一个 REST 服务的返回类型,其中包含一个 Long 字段。当该字段为 NULL 时,返回的 XML 会跳过该字段。我希望该字段作为空元素出现在输出中。

例如:如果 POJO 定义如下:

class Employee
{
  String name;
  Integer rating;
}

返回的XML为

<root><employee><name>John</name></employee></root>

而我希望它是:

<root><employee><name>John</name><rating></rating></employee></root>

为了做到这一点,我按照http://cxf.apache.org/docs/jax-rs-basics.html#JAX-RSBasics-MessageBodyProviders中的说明编写了一个自定义messagebodywriter。

@Produces("text/plain")
public class NullableLongWriter implements MessageBodyWriter<Long> {

    public long getSize(Long l, Class<?> type, Type genericType, Annotation[] annotations, MediaType mt) {
        return -1;
    }

    public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mt) {
        return long.class.isAssignableFrom(type) || Long.class.isAssignableFrom(type);
    }

    public void writeTo(Long l, Class<?> clazz, Type type, Annotation[] a,
                        MediaType mt, MultivaluedMap<String, Object> headers, OutputStream os)
            throws IOException
    {
        if (l == null)
            os.write("".toString().getBytes());
        else
            os.write(l.toString().getBytes());

    }
}

但它没有被调用为 Long 类型。仅针对 Employee 类调用它。

如何为所有类型调用自定义消息正文编写器?

最佳答案

如果您的 Controller 返回 Long 值,则将使用您的 NullableLongWriter。它不用于序列化 Employee 类的长字段。

但是您可以使用 JAXB 注释影响 Pojo 的 XML 序列化:

@XmlAccessorType(XmlAccessType.FIELD)
class Employee
{
     String name;
     @XmlElement(nillable=true)
     Integer rating;
}

您的示例将被序列化为

<employee>
    <name>John</name>
    <rating xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="true"/>
</employee>

这相当难看。为什么您不接受评级元素不在 XML 中?

关于java - 未调用 Long 数据类型的自定义 MessageBodyWriter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31436932/

相关文章:

java - 从其他类调用非静态方法

php - 我收到一个 fb_authToken 并想通过 fb_id 使用 PHP 验证它是否具有 session 和/或属于用户

log4j - 如何使用 Log4j 记录 Apache CXF Soap 请求和 Soap 响应?

http - 如何对多个项目使用 ETag/If-Match

http - 如何删除传输编码 : chunked in the HTTP response

java - 如何仅为特定端点添加 Apache cxf wsrm

tomcat - 从身份服务器验证的应用程序调用 Web 服务

java - 将两个已排序的数组列表合并为一个已排序的数组列表

java - 无法解析 localTime 中的可选微秒

java - SWIG Java 保留从 C++ 弹回的对象的类信息