Class JSON

java.lang.Object
dev.gmitch215.bytebox.json.JSON

public final class JSON extends Object
Converts between Java types and JSON, through codecs rather than reflection.

The Gradle plugin generates and registers a codec for every type annotated JSONType, so the common case needs nothing but the annotation:

 @JSONType
 public record Settings(String host, int port) {}

 Settings settings = request.json(Settings.class);

Nothing here reflects. A reflective decoder would have to keep field metadata for every type that could arrive through an Object-typed field, which is the whole-program closure dead code elimination exists to prune — so the size of the binary would depend on how many types were serialisable rather than on how many were used.

Request.json(java.util.function.Function) is the escape hatch for a type with no codec, and costs nothing at build time.

Since:
1.0.0
  • Method Details

    • register

      public static <T> void register(Class<T> type, Codec<T> codec)
      Registers a codec.

      Called from the generated registration class during module evaluation. Registering the same type twice replaces the earlier codec, so a hand-written one can override a generated one.

      Type Parameters:
      T - the type
      Parameters:
      type - the type
      codec - the codec
    • handles

      public static boolean handles(Class<?> type)
      Whether a type has a codec.
      Parameters:
      type - the type
      Returns:
      whether it can be converted
    • decode

      public static <T> T decode(TSObject value, Class<T> type)
      Reads a JavaScript value as a Java type.
      Type Parameters:
      T - the type
      Parameters:
      value - the JavaScript value
      type - the type
      Returns:
      the Java value, or null when the JavaScript value was null
    • encode

      public static <T> TSObject encode(T value, Class<T> type)
      Writes a Java value as a JavaScript value.
      Type Parameters:
      T - the type
      Parameters:
      value - the Java value
      type - the type
      Returns:
      the JavaScript value
    • parse

      public static <T> T parse(String json, Class<T> type)
      Parses JSON text as a Java type.
      Type Parameters:
      T - the type
      Parameters:
      json - the JSON
      type - the type
      Returns:
      the Java value
    • stringify

      public static <T> String stringify(T value, Class<T> type)
      Serialises a Java value as JSON text.
      Type Parameters:
      T - the type
      Parameters:
      value - the Java value
      type - the type
      Returns:
      the JSON