如何使用 Jersey REST 序列化 Java 原语 [英] How to serialize Java primitives using Jersey REST

查看:37
本文介绍了如何使用 Jersey REST 序列化 Java 原语的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序中,我使用 Jersey REST 来序列化复杂的对象.这工作得很好.但是有一些方法只返回一个 int 或 boolean.

In my application I use Jersey REST to serialize complex objects. This works quite fine. But there are a few method which simply return an int or boolean.

Jersey 无法处理原始类型(据我所知),可能是因为它们没有注释并且 Jersey 没有默认注释.我通过创建复杂类型(如 RestBoolean 或 RestInteger)来解决这个问题,这些类型只包含一个 int 或 boolean 值并具有适当的注释.

Jersey can't handle primitive types (to my knowledge), probably because they're no annotated and Jersey has no default annotation for them. I worked around that by creating complex types like a RestBoolean or RestInteger, which simply hold an int or boolean value and have the appropriate annotations.

难道没有比编写这些容器对象更简单的方法吗?

Isn't there an easier way than writing these container objects?

推荐答案

看看 Genson.它帮我解决了一个类似的问题.有了 Genson,你可以使用泛型,比如 int、boolean、lists 等等......这是一个简单的例子.

Have a look at Genson.It helped me a lot with a similar problem.With Genson you could use generics like int,boolean, lists and so on...Here is a quick example.

@GET
@Produces(MediaType.APPLICATION_JSON)
public Response getMagicList() {
    List<Object> objList = new ArrayList<>();
    stringList.add("Random String");
    stringList.add(121); //int
    stringList.add(1.22); //double
    stringList.add(false); //bolean

    return Response.status(Status.OK).entity(objList).build();
}

这将产生一个有效的 JSON 女巫,可以像这样非常简单地检索:

This will produce a valid JSON witch can be retrieved very simple like this:

    Client client = Client.create();
    WebResource webResource = client.resource("...path to resource...");
    List objList = webResource.accept(MediaType.APPLICATION_JSON).get(ArrayList.class);
    for (Object obj : objList) {
        System.out.println(obj.getClass());
    }

您将看到 Genson 还将帮助您在客户端解码 JSON 并为每个输出正确的类.

You will see that Genson will help you decode the JSON on the client side also and output the correct class for each.

这篇关于如何使用 Jersey REST 序列化 Java 原语的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆