Search code examples
jsonjax-rsresteasystringify

Use JSON.stringify and JSON.parse in resteasy


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.


Solution

  • 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
    }