方法一:使用 Jackson(推薦,Spring Boot 默認)

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JsonChineseKeyExample {
    public static void main(String[] args) throws Exception {
        String json = """
            {
              "姓名": "張三",
              "年齡": 25,
              "城市": "北京"
            }
            """;

        ObjectMapper mapper = new ObjectMapper();
        JsonNode root = mapper.readTree(json);

        // 直接用中文 key 獲取
        String name = root.get("姓名").asText();   // "張三"
        int age = root.get("年齡").asInt();        // 25
        String city = root.get("城市").asText();   // "北京"

        System.out.println("姓名: " + name);
        System.out.println("年齡: " + age);
        System.out.println("城市: " + city);
    }
}

✅ 優點:類型安全、性能好、支持流式解析。

方法二:使用 Gson(Google 出品)

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

public class GsonExample {
    public static void main(String[] args) {
        String json = "{\"姓名\":\"張三\",\"年齡\":25,\"城市\":\"北京\"}";

        JsonObject obj = JsonParser.parseString(json).getAsJsonObject();

        String name = obj.get("姓名").getAsString();   // "張三"
        int age = obj.get("年齡").getAsInt();          // 25
        String city = obj.get("城市").getAsString();   // "北京"

        System.out.println(name + ", " + age + "歲, " + city);
    }
}

💡 注意:Gson 的 JsonParser.parseString() 在較新版本中已棄用,可改用:

JsonObject obj = JsonParser.parseString(json).getAsJsonObject(); // 或 JsonObject obj = new Gson().fromJson(json, JsonObject.class);

方法三:使用 Fastjson(阿里出品,國內常用)

import com.alibaba.fastjson2.JSONObject;

public class FastjsonExample {
    public static void main(String[] args) {
        String json = "{\"姓名\":\"張三\",\"年齡\":25,\"城市\":\"北京\"}";

        JSONObject obj = JSONObject.parseObject(json);

        String name = obj.getString("姓名");   // "張三"
        Integer age = obj.getInteger("年齡");  // 25
        String city = obj.getString("城市");   // "北京"

        System.out.println(name + " | " + age + " | " + city);
    }
}

⚠️ 注意:Fastjson 有多個版本(1.x 和 2.x),API 略有不同。以上為 fastjson2(推薦使用新版)。

方法四:轉換為 Map(通用方式)

如果你不想依賴特定 JSON 節點類型,可以轉成 Map<String, Object>

// Jackson 示例
ObjectMapper mapper = new ObjectMapper();
Map<String, Object> map = mapper.readValue(json, Map.class);

String name = (String) map.get("姓名");
Integer age = (Integer) map.get("年齡");