Question

I'm using jersey, and jackson for formatting JSON output.

The Java source looks like this:

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import javax.json.Json;
import javax.json.JsonObject;

@Path("/hello")
public class Hello {

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public JsonObject reservations() {
        JsonObject result = Json.createObjectBuilder()
            .add("hello","world")
            .add("name", "Bowes")
            .add("id", "4E37071A-CB20-49B8-9C82-F2A39639C1A3")
            .add("age", 25)
            .build();
        return result;
    }
}

I have a dependency on Jackson in the pom.xml file, like this:

<!-- avoid this message:
     org.glassfish.jersey.message.internal.MessageBodyProviderNotFoundException:
     MessageBodyWriter not found for media type=application/json -->
<dependency>
  <groupId>com.fasterxml.jackson.jaxrs</groupId>
  <artifactId>jackson-jaxrs-json-provider</artifactId>
  <version>2.3.3</version>
</dependency>

Today the output looks like this:

{"hello":{"chars":"world","string":"world","valueType":"STRING"},"name":{"chars":"Bowes","string":"Bowes","valueType":"STRING"},"id":{"chars":"4E37071A-CB20-49B8-9C82-F2A39639C1A3","string":"4E37071A-CB20-49B8-9C82-F2A39639C1A3","valueType":"STRING"},"age":{"integral":true,"valueType":"NUMBER"}}

I really want it to be formatted and to omit the "chars" and "valueType" fields. like this:

{
  "hello": "world",
  "name": "Bowes",
  "id": "4E37071A-CB20-49B8-9C82-F2A39639C1A3",
  "age": 25
}

How can I do this?

Was it helpful?

Solution

I believe the issue is caused because you are returning a JsonObject and not a String. Serializing the JsonObject needs, by default, to return enough information to be able to recreate it on de-serialization.

You can either use a JsonWriter to convert it to a String and return that or, better yet, create a local static class with your fields and simply return the object. Since your method is marked as returning JSON, Jersey/Jackson will automatically serialize your object for you. Depending on your Jackson settings, you may need to annotate your class so Jackson knows what to do with it.

@JsonAutoDetect(fieldVisibility = Visibility.ANY)
private static class MyReturn {
    String hello;
    String name;
    UUID id;
    int age;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top