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

查看:97
本文介绍了如何使用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无法处理原始类型(据我所知),可能是因为它们没有注释,泽西岛没有默认的注释。我通过创建像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,list等泛型......这是一个简单的例子。

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天全站免登陆