Class Jackson


  • public abstract class Jackson
    extends Object
    Provides key integration points with the Jackson support for dealing with JSON.

    Rendering as JSON

    The methods that return a JsonRender are to be used with the Context.render(Object) method for serializing objects to the response as JSON.

    
     import ratpack.test.embed.EmbeddedApp;
     import ratpack.core.jackson.Jackson;
     import ratpack.core.http.client.ReceivedResponse;
     import com.fasterxml.jackson.databind.ObjectMapper;
    
     import static ratpack.core.jackson.Jackson.json;
     import static org.junit.jupiter.api.Assertions.*;
    
     public class Example {
    
       public static class Person {
         private final String name;
         public Person(String name) {
           this.name = name;
         }
         public String getName() {
           return name;
         }
       }
    
       public static void main(String... args) throws Exception {
         EmbeddedApp.of(s -> s
           .handlers(chain ->
             chain.get(ctx -> ctx.render(json(new Person("John"))))
           )
         ).test(httpClient -> {
           ReceivedResponse response = httpClient.get();
           assertEquals("{\"name\":\"John\"}", response.getBody().getText());
           assertEquals("application/json", response.getBody().getContentType().getType());
         });
       }
     }
     

    Streaming JSON

    The chunkedJsonList(Registry, Publisher) method can be used for rendering a very large JSON stream/list without buffering the entire list in memory.

    Parsing JSON requests

    The methods that return a Parse are to be used with the Context.parse(ratpack.core.parse.Parse) method for deserializing request bodies containing JSON.

    
     import ratpack.test.embed.EmbeddedApp;
     import ratpack.core.jackson.Jackson;
     import ratpack.core.http.client.ReceivedResponse;
     import com.fasterxml.jackson.databind.JsonNode;
     import com.fasterxml.jackson.databind.ObjectMapper;
     import com.fasterxml.jackson.annotation.JsonProperty;
     import com.google.common.reflect.TypeToken;
    
     import java.util.List;
    
     import static ratpack.func.Types.listOf;
     import static ratpack.core.jackson.Jackson.jsonNode;
     import static ratpack.core.jackson.Jackson.fromJson;
     import static org.junit.jupiter.api.Assertions.*;
    
     public class Example {
    
       public static class Person {
         private final String name;
         public Person(@JsonProperty("name") String name) {
           this.name = name;
         }
         public String getName() {
           return name;
         }
       }
    
       public static void main(String... args) throws Exception {
         EmbeddedApp.of(s -> s
           .handlers(chain -> chain
             .post("asNode", ctx -> {
               ctx.render(ctx.parse(jsonNode()).map(n -> n.get("name").asText()));
             })
             .post("asPerson", ctx -> {
               ctx.render(ctx.parse(fromJson(Person.class)).map(p -> p.getName()));
             })
             .post("asPersonList", ctx -> {
               ctx.render(ctx.parse(fromJson(listOf(Person.class))).map(p -> p.get(0).getName()));
             })
           )
         ).test(httpClient -> {
           ReceivedResponse response = httpClient.requestSpec(s ->
             s.body(b -> b.type("application/json").text("{\"name\":\"John\"}"))
           ).post("asNode");
           assertEquals("John", response.getBody().getText());
    
           response = httpClient.requestSpec(s ->
             s.body(b -> b.type("application/json").text("{\"name\":\"John\"}"))
           ).post("asPerson");
           assertEquals("John", response.getBody().getText());
    
           response = httpClient.requestSpec(s ->
             s.body(b -> b.type("application/json").text("[{\"name\":\"John\"}]"))
           ).post("asPersonList");
           assertEquals("John", response.getBody().getText());
         });
       }
     }
     

    A NoOptParserSupport parser is also rendered for the "application/json" content type. This allows the use of the Context.parse(java.lang.Class) and Context.parse(com.google.common.reflect.TypeToken) methods.

    
     import ratpack.test.embed.EmbeddedApp;
     import ratpack.core.jackson.Jackson;
     import ratpack.core.http.client.ReceivedResponse;
     import com.fasterxml.jackson.annotation.JsonProperty;
     import com.fasterxml.jackson.databind.ObjectMapper;
     import com.google.common.reflect.TypeToken;
    
     import java.util.List;
    
     import static ratpack.func.Types.listOf;
     import static org.junit.jupiter.api.Assertions.*;
    
     public class Example {
    
       public static class Person {
         private final String name;
         public Person(@JsonProperty("name") String name) {
           this.name = name;
         }
         public String getName() {
           return name;
         }
       }
    
       public static void main(String... args) throws Exception {
         EmbeddedApp.of(s -> s
           .handlers(chain -> chain
             .post("asPerson", ctx -> {
               ctx.parse(Person.class).then(person -> ctx.render(person.getName()));
             })
             .post("asPersonList", ctx -> {
               ctx.parse(listOf(Person.class)).then(person -> ctx.render(person.get(0).getName()));
             })
           )
         ).test(httpClient -> {
           ReceivedResponse response = httpClient.requestSpec(s ->
             s.body(b -> b.type("application/json").text("{\"name\":\"John\"}"))
           ).post("asPerson");
           assertEquals("John", response.getBody().getText());
    
           response = httpClient.requestSpec(s ->
             s.body(b -> b.type("application/json").text("[{\"name\":\"John\"}]"))
           ).post("asPersonList");
           assertEquals("John", response.getBody().getText());
         });
       }
     }
     

    Configuring Jackson

    The Jackson API is based around the ObjectMapper. Ratpack adds a default instance to the base registry automatically. To configure Jackson behaviour, override this instance.

    
     import ratpack.test.embed.EmbeddedApp;
     import ratpack.core.http.client.ReceivedResponse;
     import com.fasterxml.jackson.databind.ObjectMapper;
     import com.fasterxml.jackson.datatype.jdk8.Jdk8Module;
    
     import java.util.Optional;
    
     import static ratpack.core.jackson.Jackson.json;
     import static org.junit.jupiter.api.Assertions.*;
    
     public class Example {
    
       public static class Person {
         private final String name;
         public Person(String name) {
           this.name = name;
         }
         public String getName() {
           return name;
         }
       }
    
       public static void main(String... args) throws Exception {
         EmbeddedApp.of(s -> s
           .registryOf(r -> r
             .add(new ObjectMapper().registerModule(new Jdk8Module()))
           )
           .handlers(chain ->
             chain.get(ctx -> {
               Optional<Person> personOptional = Optional.of(new Person("John"));
               ctx.render(json(personOptional));
             })
           )
         ).test(httpClient -> {
           ReceivedResponse response = httpClient.get();
           assertEquals("{\"name\":\"John\"}", response.getBody().getText());
           assertEquals("application/json", response.getBody().getContentType().getType());
         });
       }
     }
     
    • Method Detail

      • json

        public static JsonRender json​(Object object)
        Creates a renderable object to render the given object as JSON.

        The given object will be converted to JSON using an ObjectWriter obtained from the context registry.

        See the rendering section for usage examples.

        Parameters:
        object - the object to render as JSON
        Returns:
        a renderable wrapper for the given object
      • json

        public static JsonRender json​(Object object,
                                      @Nullable
                                      ObjectWriter objectWriter)
        Creates a renderable object to render the given object as JSON.

        The given object will be converted to JSON using the given ObjectWriter. If it is null, an ObjectWriter will be obtained from the context registry.

        See the rendering section for usage examples.

        Parameters:
        object - the object to render as JSON
        objectWriter - the object writer to use to serialize the object to JSON
        Returns:
        a renderable wrapper for the given object
      • json

        public static JsonRender json​(Object object,
                                      @Nullable
                                      Class<?> viewClass)
        Creates a renderable object to render the given object as JSON.

        The given object will be converted to JSON using an ObjectWriter obtained from the context registry with the specified view Class used to determine which fields are included. If it is null the default view rendering of the ObjectWriter will be used.

        See the rendering section for usage examples.

        Parameters:
        object - the object to render as JSON
        viewClass - the view to use when rendering
        Returns:
        a renderable wrapper for the given object
      • json

        public static JsonRender json​(Object object,
                                      @Nullable
                                      ObjectWriter objectWriter,
                                      @Nullable
                                      Class<?> viewClass)
        Creates a renderable object to render the given object as JSON.

        The given object will be converted to JSON using the given ObjectWriter with the specified view Class used to determine which fields are included. If the ObjectWriter is null, an ObjectWriter will be obtained from the context registry. If the view Class is null the default view rendering of the ObjectWriter will be used.

        See the rendering section for usage examples.

        Parameters:
        object - the object to render as JSON
        objectWriter - the object writer to use to serialize the object to JSON
        viewClass - the view to use when rendering
        Returns:
        a renderable wrapper for the given object
      • jsonNode

        public static Parse<JsonNode,​JsonParseOpts> jsonNode()
        Creates a parseable object to parse a request body into a JsonNode.

        The corresponding parser for this type requires the request content type to be "application/json".

        The request body will be parsed using an ObjectMapper obtained from the context registry.

        See the parsing section for usage examples.

        Returns:
        a parse object
      • jsonNode

        public static Parse<JsonNode,​JsonParseOpts> jsonNode​(@Nullable
                                                                   ObjectMapper objectMapper)
        Creates a parseable object to parse a request body into a JsonNode.

        The corresponding parser for this type requires the request content type to be "application/json".

        The request body will be parsed using the given ObjectMapper. If it is null, a mapper will be obtained from the context registry.

        See the parsing section for usage examples.

        Parameters:
        objectMapper - the object mapper to use to parse the JSON
        Returns:
        a parse object
      • fromJson

        public static <T> Parse<T,​JsonParseOpts> fromJson​(Class<T> type)
        Creates a parseable object to parse a request body into the given type.

        The corresponding parser for this type requires the request content type to be "application/json".

        The request body will be parsed using an ObjectMapper obtained from the context registry.

        See the parsing section for usage examples.

        Type Parameters:
        T - the type of object to deserialize the JSON into
        Parameters:
        type - the type of object to deserialize the JSON into
        Returns:
        a parse object
      • fromJson

        public static <T> Parse<T,​JsonParseOpts> fromJson​(com.google.common.reflect.TypeToken<T> type)
        Creates a parseable object to parse a request body into the given type.

        The corresponding parser for this type requires the request content type to be "application/json".

        The request body will be parsed using an ObjectMapper obtained from the context registry.

        See the parsing section for usage examples.

        Type Parameters:
        T - the type of object to deserialize the JSON into
        Parameters:
        type - the type of object to deserialize the JSON into
        Returns:
        a parse object
      • fromJson

        public static <T> Parse<T,​JsonParseOpts> fromJson​(Class<T> type,
                                                                @Nullable
                                                                ObjectMapper objectMapper)
        Creates a parseable object to parse a request body into the given type.

        The corresponding parser for this type requires the request content type to be "application/json".

        The request body will be parsed using the given ObjectMapper. If it is null, a mapper will be obtained from the context registry.

        See the parsing section for usage examples.

        Type Parameters:
        T - the type of object to deserialize the JSON into
        Parameters:
        type - the type of object to deserialize the JSON into
        objectMapper - the object mapper to use to convert the JSON into a Java object
        Returns:
        a parse object
      • fromJson

        public static <T> Parse<T,​JsonParseOpts> fromJson​(com.google.common.reflect.TypeToken<T> type,
                                                                @Nullable
                                                                ObjectMapper objectMapper)
        Creates a parseable object to parse a request body into the given type.

        The corresponding parser for this type requires the request content type to be "application/json".

        The request body will be parsed using the given ObjectMapper. If it is null, a mapper will be obtained from the context registry.

        See the parsing section for usage examples.

        Type Parameters:
        T - the type of object to deserialize the JSON into
        Parameters:
        type - the type of object to deserialize the JSON into
        objectMapper - the object mapper to use to convert the JSON into a Java object
        Returns:
        a parse object
      • chunkedJsonList

        public static <T> ResponseChunks chunkedJsonList​(Registry registry,
                                                         Publisher<T> stream)
        Renders a data stream as a JSON list, directly streaming the JSON.

        This method differs from rendering a list of items using json(someList) in that data is written to the response as chunks, and is streamed.

        If stream can be very large without using considerable memory as the JSON is streamed incrementally in chunks. This does mean that if on object-to-JSON conversion fails midway through the stream, then the output JSON will be malformed due to being incomplete. If the publisher emits an error, the response will be terminated and no more JSON will be sent.

        
         import ratpack.test.embed.EmbeddedApp;
         import ratpack.core.jackson.Jackson;
         import ratpack.core.http.client.ReceivedResponse;
         import ratpack.exec.stream.Streams;
         import com.fasterxml.jackson.databind.ObjectMapper;
         import org.reactivestreams.Publisher;
        
         import java.util.Arrays;
        
         import static ratpack.core.jackson.Jackson.chunkedJsonList;
         import static org.junit.jupiter.api.Assertions.*;
        
         public class Example {
           public static void main(String... args) throws Exception {
             EmbeddedApp.of(s -> s
               .handlers(chain ->
                 chain.get(ctx -> {
                   Publisher<Integer> ints = Streams.publish(Arrays.asList(1, 2, 3));
                   ctx.render(chunkedJsonList(ctx, ints));
                 })
               )
             ).test(httpClient -> {
               ReceivedResponse response = httpClient.get();
               assertEquals("[1,2,3]", response.getBody().getText()); // body was streamed in chunks
               assertEquals("application/json", response.getBody().getContentType().getType());
             });
           }
         }
         

        Items of the stream will be converted to JSON by an ObjectMapper obtained from the given registry.

        This method uses Streams.streamMap(Publisher, StreamMapper) to consume the given stream.

        Type Parameters:
        T - the type of item in the stream
        Parameters:
        registry - the registry to obtain the object mapper from
        stream - the stream to render
        Returns:
        a renderable object
        See Also:
        Streams.streamMap(Publisher, StreamMapper)
      • chunkedJsonList

        public static <T> ResponseChunks chunkedJsonList​(ObjectWriter objectWriter,
                                                         Publisher<T> stream)
        Renders a data stream as a JSON list, directly streaming the JSON.

        Identical to chunkedJsonList(Registry, Publisher), except uses the given object writer instead of obtaining one from the registry.

        Type Parameters:
        T - the type of item in the stream
        Parameters:
        objectWriter - the object write to use to convert stream items to their JSON representation
        stream - the stream to render
        Returns:
        a renderable object
        See Also:
        chunkedJsonList(Registry, Publisher)