Class JsonHelper

java.lang.Object
com.loomcache.server.rest.JsonHelper

public class JsonHelper extends Object
Simple JSON serialization/deserialization helper without external dependencies. Supports maps, lists, primitives, strings, and nested structures.

Thread-safe: All methods are stateless and can be called concurrently.

Limitations: - Custom object serialization requires objects to implement toString() or be Maps/Lists - Deserialization supports basic types only (Map, List, String, Number, Boolean)

Used by RestApiServer to handle JSON request/response bodies.

  • Method Details

    • toJson

      public static String toJson(@Nullable Object obj)
      Serialize an object to JSON string.

      Supports: - null → "null" - String → "\"escaped string\"" - Number → unquoted numeric value - Boolean → "true" or "false" - Map → {"key": value, ...} - List → [value, value, ...] - Arrays → [value, value, ...] - Other objects → their toString() representation

      Parameters:
      obj - the object to serialize (may be null)
      Returns:
      JSON string representation (non-null)
    • fromJson

      public static <T> @Nullable T fromJson(String json, Class<T> clazz)
      Deserialize a JSON string to an object of the specified type.

      Type conversion rules: - String.class: parse as string or use parsed value's toString() - Map.class: parse as object, or return empty map if parse result is not a map - List.class: parse as array, or return empty list if parse result is not a list - Other: return parsed value as-is

      Type Parameters:
      T - the type parameter
      Parameters:
      json - the JSON string (non-null, non-empty after trimming)
      clazz - the target class (currently supports Map.class, List.class, String.class, Number.class)
      Returns:
      deserialized object, or null if the JSON literal is "null"
      Throws:
      NullPointerException - if json or clazz is null
      IllegalArgumentException - if json is empty or only whitespace