Class JsonHelper
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 Summary
-
Method Details
-
toJson
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
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 nullIllegalArgumentException- if json is empty or only whitespace
-