Working with JSON in RESTful applications

Last Updated on

There are many JSON libraries that make JSON works possible in a Java application. When responding HTTP response that should be in JSON format we should use the annotation:


With the Http Methods Get, Post, Delete, Put and Patch, we should consider the respective annotation, i.e. @GET, @POST, @DELETE, @PUT and @PATCH.

Since it is desirable that RESTful Java apps reply through JSON objects, we do responses in JSON format.

One way would be to write a String variable but use the curly brackets and backslashes as in

String var1 = "{\"Hello\":\"world\"}";

return Response.ok(var1).build();

Another way would be to use a library package like Gson. More reading can be found at:

            JSONObject obj = new JSONObject();
            obj.put("name", "foo");
            String json = new Gson().toJson(obj);
            return Response.ok(json).build();
            /* Returns:
                "map": {
                "name": "foo"

Its Maven dependency would be:


Another technique is using the org.json’s JSONObject and to use its .toString at return time:

            JSONObject obj = new JSONObject();
            obj.put("name", "foo");
            return Response.ok(obj.toString()).build();

Its dependency is as follows and more reading can be found at ttps://

    <!-- -->

Java applications using the Jersey implementation for RESTful Java apps can use the Jersey media dependency. More reading on this can be found at: where we see that the right Maven dependency can help in returning JSON objects from Java variables:

    <version>{latest version}</version>

For example to return a List variable in JSON format using the above dependency, we can write code where we use the @POST annotation, prepare a list of persons and return via Response.ok(persons).build.

    public Response all() {
        Person p1 = new Person (1, "Bob", "", "0123456789", "123 Main St.");
        Person p2 = new Person (2, "Bob2", "", "0987654321", "456 Main St.");
        Person p3 = new Person (3, "Bob3", "", "0700123456", "789 Main Street");
        List<Person> persons = new ArrayList<Person>();
        //good resources:
        // //java - webservices - jersey return arraylist json

        System.out.println("List: " + persons);

        return Response.ok(persons).build(); //this works
        //return Response.ok().entity(persons).build(); //this works also


A more complete example as an IntelliJ IDEA project, with a GET and a POST method and their JSON Response can be downloaded here.

Other resources:

Lämna ett svar