Use JSON.stringify and JSON.parse in resteasy

放肆的年华 提交于 2019-12-11 14:48:43

问题


I need to use JSON.stringify and JSON.parse in a java class that contains resteasy services to exchange information with a Jquery script. Which library should import the java class or what should I do ?, because in the script itself let me do it by default. Thank you very much.


回答1:


So from my understanding you want to be able to serialize and deserialize JSON to and from Java object, as that's what JSON.stringify and JSON.parse does for Javascript.

To be able to handle that, we need a MessageBodyReader and a MessageBodyWriter to handle the conversion. The Resteasy has the providers available as part of the framework. We just need to add the module.

Hopefully you are using Maven, if not see this post. With Maven you should have either one of these dependencies

<dependency>
    <groupId>org.jboss.resteasy</groupId>
    <artifactId>resteasy-jackson-provider</artifactId>
    <version>${resteasy.version}</version>
</dependency>
<dependency>
    <groupId>org.jboss.resteasy</groupId>
    <artifactId>resteasy-jackson2-provider</artifactId>
    <version>${resteasy.version}</version>
</dependency>

The only difference is in which Jackson flavor will be used 1.x or 2.x

Once you have to provider on the classpath, it should be auto configured. All you need to do is use your POJO ad the conversion will be done e.g

@GET
@Produces("application/json")
public Response getMyPojo() {
    MyPojo pojo = new MyPojo();
    return Response.ok(pojo).build();
}

@POST
@Consumes("application/json")
public Response createMyPojo( MyPojo pojo ) {
    // do something with pojo
}


来源:https://stackoverflow.com/questions/27168350/use-json-stringify-and-json-parse-in-resteasy

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