How to serialize Java primitives using Jersey REST

前端 未结 6 1965
灰色年华
灰色年华 2020-11-29 11:47

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 can

6条回答
  •  既然无缘
    2020-11-29 12:14

    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 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();
    }
    
    
    

    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());
        }
    

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

    提交回复
    热议问题