Class FormatDetector

java.lang.Object
cloud.opencode.base.serialization.FormatDetector

public final class FormatDetector extends Object
FormatDetector - Serialization Format Auto-Detection Utility 序列化格式自动检测工具类

Detects the serialization format of byte array data by inspecting header byte patterns. Supports detection of JSON, XML, and Protobuf formats.

通过检查头部字节模式来检测字节数组数据的序列化格式。 支持检测 JSON、XML 和 Protobuf 格式。

Features | 主要功能:

  • JSON detection (starts with '{', '[', '"' or whitespace before these) - JSON 检测
  • XML detection (starts with '<' or BOM + '<') - XML 检测
  • Protobuf detection (wire type pattern analysis) - Protobuf 检测(wire type 模式分析)
  • Returns "unknown" for unrecognized formats - 无法识别的格式返回 "unknown"

Usage Examples | 使用示例:

byte[] data = ...; // some serialized data

String format = FormatDetector.detect(data);  // "json", "xml", "protobuf", or "unknown"
boolean json = FormatDetector.isJson(data);    // true/false
boolean xml  = FormatDetector.isXml(data);     // true/false

Security | 安全性:

  • Thread-safe: Yes (stateless utility) - 线程安全: 是(无状态工具类)
Since:
JDK 25, opencode-base-serialization V1.0.3
Author:
Leon Soo www.LeonSoo.com
See Also:
  • Field Details

  • Method Details

    • detect

      public static String detect(byte[] data)
      Detects the serialization format of the given data. 检测给定数据的序列化格式。

      Detection is based on header byte analysis:

      • JSON: first non-whitespace byte is '{', '[', or '"'
      • XML: first non-whitespace byte is '<' (with optional BOM)
      • Protobuf: valid wire type in first byte's lower 3 bits
      • Otherwise: "unknown"
      Parameters:
      data - the data to inspect | 要检测的数据
      Returns:
      the detected format name ("json", "xml", "protobuf", or "unknown") | 检测到的格式名称
    • isJson

      public static boolean isJson(byte[] data)
      Checks if the data appears to be JSON format. 检查数据是否为 JSON 格式。

      JSON data starts with '{', '[', or '"' (possibly preceded by whitespace or BOM).

      JSON 数据以 '{'、'[' 或 '"' 开头(可能前面有空白字符或 BOM)。

      Parameters:
      data - the data to check | 要检查的数据
      Returns:
      true if the data appears to be JSON | 如果数据看起来是 JSON 则返回 true
    • isXml

      public static boolean isXml(byte[] data)
      Checks if the data appears to be XML format. 检查数据是否为 XML 格式。

      XML data starts with '<' (possibly preceded by BOM or whitespace).

      XML 数据以 '<' 开头(可能前面有 BOM 或空白字符)。

      Parameters:
      data - the data to check | 要检查的数据
      Returns:
      true if the data appears to be XML | 如果数据看起来是 XML 则返回 true