how to get JSON representation of Java Objects in JAX-RS layer in java EE 7?

杀马特。学长 韩版系。学妹 提交于 2019-12-13 02:23:22

问题


We are currently using Java EE 5 and we do something like the following for turning POJO into JSON before sending the response.

    @GET
    @Path("/books")
    @Produces(MediaType.APPLICATION_JSON)
    public Response getBooks()  {
    List<Book> listOfBooks = getMiscService().getbooks();
    String response = "{\"books\":" + gson.toJson(listOfBooks) + "}";               
    return Response.status(Response.Status.OK).entity(response).build();
    }

we are using gson API of google. Now that we are restructuring the code to Java EE 7 API compliant, I am wondering if there is any JSON converting API that will convert POJO into JSON.

I am aware of JsonObject API introduced in Java EE 7. But I am still wondering how will I get JSON representation of my POJO.

JsonObject jsonObject = Json.createObjectBuilder().add("books", myObject);

myObject above needs to be JSON representation of my object correct?

I am thinking along this. but this still uses Gson

JsonObject jsonObject = Json.createObjectBuilder().add("books", gson.toJson(myObject));

what is the recommended way here?

Thank you


回答1:


JAX-RS will convert your objects to JSON, no need to do it manually. I.e., the following code:

@GET
@Path("/books")
@Produces(MediaType.APPLICATION_JSON)
public Response getBooks()  {
    List<Book> listOfBooks = getMiscService().getbooks();
    return Response.status(Response.Status.OK).entity(listOfBooks).build();
}

...will produce a JSON like:

[
    { "title": "Book1", "author": "Foo", ... },
    { "title": "Book2", "author": "Bar", ... },
    ...
]

If you want a books wrapper, just make a bean:

public class BooksWrapper {
    private List<Book> books;
    public BooksWrapper(List<Book> books) {
        this.books = books;
    }
    public List<Book> getBooks() {
        return books;
    }
}

And convert the REST method to return this type:

@GET
@Path("/books")
@Produces(MediaType.APPLICATION_JSON)
public Response getBooks()  {
    List<Book> listOfBooks = getMiscService().getbooks();
    BooksWrapper result = new BooksWrapper(listOfBooks);
    return Response.status(Response.Status.OK).entity(result).build();
}


来源:https://stackoverflow.com/questions/28079195/how-to-get-json-representation-of-java-objects-in-jax-rs-layer-in-java-ee-7

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!