CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/maven-cn-hutool--hutool-all

A comprehensive Java utility library providing static method wrappers for common operations to reduce API learning costs and improve development efficiency

Pending
Overview
Eval results
Files

json-processing.mddocs/

JSON Processing

Comprehensive JSON utilities through the JSONUtil class, providing parsing, generation, and manipulation operations with JSONObject, JSONArray, and JSONPath support.

Import

import cn.hutool.json.JSONUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONPath;

JSON Creation

Creating JSON Objects

// Create empty JSON objects
public static JSONObject createObj();
public static JSONArray createArray();

// Create from existing data
public static JSONObject createObj(Object... keysAndValues);

Usage Examples:

// Create empty objects
JSONObject obj = JSONUtil.createObj();
JSONArray arr = JSONUtil.createArray();

// Create with initial data
JSONObject user = JSONUtil.createObj()
    .put("id", 1)
    .put("name", "John Doe")
    .put("email", "john@example.com")
    .put("active", true);

// Create from key-value pairs
JSONObject config = JSONUtil.createObj(
    "timeout", 5000,
    "retries", 3,
    "debug", false
);

JSON Parsing

Parse from String

// Parse JSON objects
public static JSONObject parseObj(String jsonStr);
public static JSONObject parseObj(Object obj);

// Parse JSON arrays
public static JSONArray parseArray(String jsonStr);
public static JSONArray parseArray(Object obj);

// Generic parsing
public static Object parse(String jsonStr);
public static Object parse(Object obj);

Parse from Files and Streams

// Parse from file
public static JSONObject readJSONObject(File file, Charset charset);
public static JSONArray readJSONArray(File file, Charset charset);

// Parse from InputStream
public static JSONObject readJSONObject(InputStream inputStream, Charset charset);
public static JSONArray readJSONArray(InputStream inputStream, Charset charset);

Usage Examples:

// Parse JSON string
String jsonStr = "{\"name\":\"John\",\"age\":30,\"skills\":[\"Java\",\"Python\"]}";
JSONObject user = JSONUtil.parseObj(jsonStr);

// Parse array
String arrayStr = "[{\"id\":1,\"name\":\"Alice\"},{\"id\":2,\"name\":\"Bob\"}]";
JSONArray users = JSONUtil.parseArray(arrayStr);

// Parse from file
JSONObject config = JSONUtil.readJSONObject(new File("config.json"), CharsetUtil.UTF_8);

JSON Object Operations

JSONObject Class

public class JSONObject extends LinkedHashMap<String, Object> {
    // Creation
    public JSONObject();
    public JSONObject(String jsonStr);
    public JSONObject(Object bean);
    
    // Value operations
    public JSONObject put(String key, Object value);
    public JSONObject putOpt(String key, Object value);
    public JSONObject putAll(Map<String, Object> map);
    
    // Get operations with type conversion
    public Object get(String key);
    public <T> T get(String key, Class<T> type);
    public String getStr(String key);
    public Integer getInt(String key);
    public Long getLong(String key);
    public Double getDouble(String key);
    public Boolean getBool(String key);
    public Date getDate(String key);
    public JSONObject getJSONObject(String key);
    public JSONArray getJSONArray(String key);
    
    // Safe get operations with defaults
    public String getStr(String key, String defaultValue);
    public Integer getInt(String key, Integer defaultValue);
    public Long getLong(String key, Long defaultValue);
    public Double getDouble(String key, Double defaultValue);
    public Boolean getBool(String key, Boolean defaultValue);
    
    // Utility methods
    public Set<String> keySet();
    public Collection<Object> values();
    public boolean containsKey(String key);
    public boolean isEmpty();
    public int size();
    public JSONObject remove(String key);
    
    // Conversion
    public String toString();
    public String toJSONString(int indentFactor);
    public <T> T toBean(Class<T> beanClass);
    public Map<String, Object> toMap();
}

JSONArray Class

public class JSONArray extends ArrayList<Object> {
    // Creation
    public JSONArray();
    public JSONArray(String jsonStr);
    public JSONArray(Collection<?> collection);
    
    // Add operations
    public JSONArray add(Object value);
    public JSONArray addAll(Collection<?> collection);
    public JSONArray put(int index, Object value);
    
    // Get operations with type conversion
    public Object get(int index);
    public <T> T get(int index, Class<T> type);
    public String getStr(int index);
    public Integer getInt(int index);
    public Long getLong(int index);
    public Double getDouble(int index);
    public Boolean getBool(int index);
    public Date getDate(int index);
    public JSONObject getJSONObject(int index);
    public JSONArray getJSONArray(int index);
    
    // Safe get operations with defaults
    public String getStr(int index, String defaultValue);
    public Integer getInt(int index, Integer defaultValue);
    public Long getLong(int index, Long defaultValue);
    public Double getDouble(int index, Double defaultValue);
    public Boolean getBool(int index, Boolean defaultValue);
    
    // Utility methods
    public int size();
    public boolean isEmpty();
    public JSONArray remove(int index);
    
    // Conversion
    public String toString();
    public String toJSONString(int indentFactor);
    public <T> List<T> toList(Class<T> elementType);
    public Object[] toArray();
}

JSON Conversion

Object to JSON

// Convert objects to JSON
public static JSONObject parseObj(Object obj);
public static JSONArray parseArray(Object obj);

// Convert with custom serialization
public static String toJsonStr(Object obj);
public static String toJsonPrettyStr(Object obj);

JSON to Object

// Convert to Java objects
public static <T> T toBean(String jsonStr, Class<T> beanType);
public static <T> T toBean(JSONObject json, Class<T> beanType);

// Convert to collections
public static <T> List<T> toList(String jsonStr, Class<T> elementType);
public static <T> List<T> toList(JSONArray jsonArray, Class<T> elementType);

// Convert to maps
public static Map<String, Object> toMap(String jsonStr);

Usage Examples:

// Object to JSON
User user = new User("John", 30, Arrays.asList("Java", "Python"));
JSONObject userJson = JSONUtil.parseObj(user);
String jsonString = JSONUtil.toJsonStr(user);

// JSON to Object
String userStr = "{\"name\":\"John\",\"age\":30,\"skills\":[\"Java\",\"Python\"]}";
User restored = JSONUtil.toBean(userStr, User.class);

// JSON to List
String usersStr = "[{\"name\":\"Alice\"},{\"name\":\"Bob\"}]";
List<User> users = JSONUtil.toList(usersStr, User.class);

JSON Path Operations

JSONPath Class

public class JSONPath {
    // Creation
    public static JSONPath of(String path);
    
    // Value extraction
    public Object getByPath(Object json);
    public <T> T getByPath(Object json, Class<T> type);
    
    // Value setting
    public void setByPath(Object json, Object value);
    
    // Path utilities
    public static Object getByPath(Object json, String path);
    public static <T> T getByPath(Object json, String path, Class<T> type);
    public static void setByPath(Object json, String path, Object value);
}

Usage Examples:

String jsonStr = """
{
  "users": [
    {"name": "John", "address": {"city": "New York"}},
    {"name": "Jane", "address": {"city": "London"}}
  ],
  "total": 2
}
""";

JSONObject json = JSONUtil.parseObj(jsonStr);

// Extract values using JSON path
String firstCity = JSONPath.getByPath(json, "$.users[0].address.city", String.class);
// Result: "New York"

Integer total = JSONPath.getByPath(json, "$.total", Integer.class);
// Result: 2

// Set values using JSON path
JSONPath.setByPath(json, "$.users[0].active", true);
JSONPath.setByPath(json, "$.lastUpdated", DateUtil.now());

JSON Utilities

Formatting and Pretty Printing

// Format JSON strings
public static String formatJsonStr(String jsonStr);
public static String formatJsonStr(String jsonStr, int indentFactor);

// Check if string is valid JSON
public static boolean isJson(String str);
public static boolean isJsonObj(String str);
public static boolean isJsonArray(String str);

JSON Comparison

// Compare JSON objects
public static boolean jsonEquals(String json1, String json2);

Usage Examples:

// Pretty print JSON
String compactJson = "{\"name\":\"John\",\"age\":30}";
String prettyJson = JSONUtil.formatJsonStr(compactJson);
/*
{
  "name": "John",
  "age": 30
}
*/

// Validate JSON
boolean isValid = JSONUtil.isJson("{\"valid\": true}");  // true
boolean isInvalid = JSONUtil.isJson("{invalid json}");   // false

// Compare JSON
boolean same = JSONUtil.jsonEquals(
    "{\"a\":1,\"b\":2}",
    "{\"b\":2,\"a\":1}"  // true - order doesn't matter
);

Configuration and Customization

JSON Configuration

// Custom JSON configuration
public static void setDateFormat(String dateFormat);
public static void setIgnoreNullValue(boolean ignoreNullValue);

Bean Conversion Options

When converting between JSON and Java objects, Hutool provides options for:

  • Date Format: Customize how dates are serialized/deserialized
  • Null Handling: Control whether null values are included
  • Property Naming: Configure property name conversion strategies
  • Type Conversion: Handle custom type conversions

Usage Examples:

// Configure date format for JSON serialization
JSONUtil.setDateFormat("yyyy-MM-dd HH:mm:ss");

// Create object with date
User user = new User();
user.setCreatedAt(new Date());

// Convert to JSON (will use configured date format)
String json = JSONUtil.toJsonStr(user);

// Configure to ignore null values
JSONUtil.setIgnoreNullValue(true);
JSONObject obj = JSONUtil.createObj()
    .put("name", "John")
    .put("email", null);  // This will be excluded from JSON string

Error Handling

JSON operations handle malformed JSON gracefully:

  • Parsing Errors: Invalid JSON strings throw JSONException
  • Type Conversion: Safe type conversion methods return defaults for incompatible types
  • Path Errors: JSONPath operations return null for non-existent paths
  • Null Safety: All operations handle null inputs appropriately

The JSON utilities provide a complete solution for working with JSON data in Java applications, with support for complex nested structures, type-safe conversions, and JSONPath queries.

Install with Tessl CLI

npx tessl i tessl/maven-cn-hutool--hutool-all

docs

additional-utilities.md

bean-object-manipulation.md

collection-utilities.md

core-string-operations.md

cryptographic-operations.md

database-access.md

date-time-handling.md

file-io-operations.md

http-client-operations.md

index.md

json-processing.md

tile.json