类 JsonUtils

java.lang.Object
io.agentscope.core.util.JsonUtils

public final class JsonUtils extends Object
Utility class for accessing the global JsonCodec instance.

This class provides a centralized way to access JSON serialization/deserialization functionality throughout the framework. By default, it uses JacksonJsonCodec, but users can replace it with a custom implementation.

Usage:


 // Basic usage
 JsonUtils.getJsonCodec().toJson(obj);
 JsonUtils.getJsonCodec().fromJson(json, MyClass.class);

 // Cache reference for frequent calls
 JsonCodec codec = JsonUtils.getJsonCodec();
 codec.toJson(obj1);
 codec.toJson(obj2);

 // Replace with custom implementation
 JsonUtils.setJsonCodec(new MyCustomJsonCodec());
 
另请参阅:
  • 方法详细资料

    • getJsonCodec

      public static JsonCodec getJsonCodec()
      Get the global JsonCodec instance.
      返回:
      the JsonCodec instance
    • setJsonCodec

      public static void setJsonCodec(JsonCodec jsonCodec)
      Set a custom JsonCodec implementation.

      This allows users to replace the default Jackson-based implementation with their own implementation (e.g., Gson, Fastjson, etc.).

      参数:
      jsonCodec - the custom JsonCodec implementation
      抛出:
      IllegalArgumentException - if jsonCodec is null
    • resetToDefault

      public static void resetToDefault()
      Reset to the default JacksonJsonCodec implementation.

      This is useful for testing or when you want to restore the default behavior.

    • isValidJsonObject

      public static boolean isValidJsonObject(String str)
      Check whether the given string is a valid JSON object (i.e. starts with '{' and can be parsed into a Map).

      Tool call arguments must be JSON objects, so plain JSON values like null, arrays, or strings are rejected.

      参数:
      str - the string to validate
      返回:
      true if str is a non-null, parseable JSON object
    • resolveToolCallArgsJson

      public static String resolveToolCallArgsJson(ToolUseBlock toolUse)
      Resolve the arguments JSON string from a ToolUseBlock, ensuring the result is always a valid JSON object.

      Resolution order:

      1. Use ToolUseBlock.getContent() if it is a valid JSON object
      2. Serialize ToolUseBlock.getInput() via JsonCodec.toJson(java.lang.Object)
      3. Fall back to "{}"

      This prevents sending malformed JSON (e.g. from interrupted streaming) as tool call arguments, which would cause model APIs to reject the request.

      参数:
      toolUse - the tool use block
      返回:
      a valid JSON object string representing the tool call arguments