Package ratpack.gson

Class Gson


  • public abstract class Gson
    extends Object
    Support for rendering and parsing JSON using Google's Gson library.
    Since:
    1.6
    • Method Detail

      • json

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

        The given object will be converted to JSON using a Gson instance 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 GsonRender json​(Object object,
                                      @Nullable
                                      com.google.gson.Gson gson)
        Creates a renderable object to render the given object as JSON.

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

        See the rendering section for usage examples.

        Parameters:
        object - the object to render as JSON
        gson - the Gson instance to use to serialize the object to JSON
        Returns:
        a renderable wrapper for the given object
      • jsonElement

        public static Parse<com.google.gson.JsonElement,​GsonParseOpts> jsonElement()
        Creates a parseable object to parse a request body into a JsonElement.

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

        The request body will be parsed using a Gson obtained from the context registry.

        See the parsing section for usage examples.

        Returns:
        a parse object
      • jsonElement

        public static Parse<com.google.gson.JsonElement,​GsonParseOpts> jsonElement​(@Nullable
                                                                                         com.google.gson.Gson gson)
        Creates a parseable object to parse a request body into a JsonElement.

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

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

        See the parsing section for usage examples.

        Parameters:
        gson - the Gson instance to use to parse the JSON
        Returns:
        a parse object
      • fromJson

        public static <T> Parse<T,​GsonParseOpts> 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 a Gson 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,​GsonParseOpts> 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 a Gson 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,​GsonParseOpts> fromJson​(Class<T> type,
                                                                @Nullable
                                                                com.google.gson.Gson gson)
        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 Gson. If it is null, a Gson instance 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
        gson - the Gson instance to use to convert the JSON into a Java object
        Returns:
        a parse object
      • fromJson

        public static <T> Parse<T,​GsonParseOpts> fromJson​(com.google.common.reflect.TypeToken<T> type,
                                                                @Nullable
                                                                com.google.gson.Gson gson)
        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 Gson. If it is null, a Gson instance 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
        gson - the Gson instance 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.gson.GsonModule;
         import ratpack.guice.Guice;
         import ratpack.test.embed.EmbeddedApp;
         import ratpack.core.http.client.ReceivedResponse;
         import ratpack.exec.stream.Streams;
         import org.reactivestreams.Publisher;
        
         import java.util.Arrays;
        
         import static ratpack.gson.Gson.chunkedJsonList;
         import static org.junit.jupiter.api.Assertions.*;
        
         public class Example {
           public static void main(String... args) throws Exception {
             EmbeddedApp.of(s -> s
               .registry(Guice.registry(b -> b.module(GsonModule.class)))
               .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 Gson 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​(com.google.gson.Gson gson,
                                                         Publisher<T> stream)
        Renders a data stream as a JSON list, directly streaming the JSON.

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

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

        public static <T> Function<T,​String> toJson​(Registry registry)
        Creates a mapping function that returns the JSON representation as a string of the input object.

        An Gson instance is obtained from the given registry eagerly. The returned function uses the Gson.toJson(Object) method to convert the input object to JSON.

        
         import ratpack.gson.GsonModule;
         import ratpack.guice.Guice;
         import ratpack.exec.Promise;
         import ratpack.test.embed.EmbeddedApp;
         import ratpack.core.http.client.ReceivedResponse;
        
         import java.util.Arrays;
        
         import static ratpack.gson.Gson.toJson;
         import static java.util.Collections.singletonMap;
         import static org.junit.jupiter.api.Assertions.*;
        
         public class Example {
           public static void main(String... args) throws Exception {
             EmbeddedApp.of(s -> s
               .registry(Guice.registry(b -> b.module(GsonModule.class)))
               .handlers(chain -> chain
                 .get(ctx ->
                   Promise.value(singletonMap("foo", "bar"))
                     .map(toJson(ctx))
                     .then(ctx::render)
                 )
               )
             ).test(httpClient -> {
               assertEquals("{\"foo\":\"bar\"}", httpClient.getText());
             });
           }
         }
         

        Note that in the above example, it would have been better to just render the result of the blocking call. Doing so would be more convenient and also set the correct "Content-Type" header. This method can be useful when sending the JSON somewhere else than directly to the response, or when mapping streams.

        Type Parameters:
        T - the type of object to convert to JSON
        Parameters:
        registry - the registry to obtain the Gson from
        Returns:
        a function that converts objects to their JSON string representation