You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java UTF-8字符转换问题求助:JSON字符串数组字符乱码

Fixing UTF-8 Encoding Issues in Your Java JSON Response

Hey there! I see you're dealing with garbled characters (like your example showing "A...") when fetching a JSON string array in Java. Let's get this sorted out quickly.

The Root Cause

The core issue here is that your InputStreamReader is using the platform default character set instead of explicitly specifying UTF-8. Most APIs return responses in UTF-8, so not setting this causes the decoder to misinterpret the raw byte data, leading to those messy garbled characters.

The Simple Fix

You just need to modify the InputStreamReader initialization to explicitly use UTF-8. Java 7+ provides StandardCharsets.UTF_8—a safe, constant way to specify this (no risk of typos from using string literals like "UTF-8").

Here's your updated code with the fix highlighted:

import java.nio.charset.StandardCharsets; // Don't forget this import!

private static void loadProperties() throws Exception {
    String properties = null;
    HttpsURLConnection con = (HttpsURLConnection) new URL(getEndpoint()).openConnection();
    // Explicitly set UTF-8 to decode the response correctly
    BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream(), StandardCharsets.UTF_8));
    String inputLine;
    StringBuffer res = new StringBuffer();
    while((inputLine = in.readLine()) != null) {
        res.append(inputLine);
    }
    in.close();
    JsonObject jsonObject = new JsonParser().parse(res.toString()).getAsJsonObject();
    if(jsonObject.has("error")) {
        JsonObject error = jsonObject.get("error").getAsJsonObject();
        if(error.has("errorCode") && "1000".equals(error.get("errorCode").getAsString()) && jsonObject.has("data")) {
            properties = jsonObject.get("data").getAsJsonArray().toString();
            log("PropertiesUtils.loadProperties: Properties = %s", properties);
            setProperties(properties);
        } else {
            throw new Exception("PropertiesUtils.loadProperties: Error while calling properties endpoint");
        }
    } else {
        throw new Exception("PropertiesUtils.loadProperties: Error while calling properties endpoint");
    }
}

Bonus: Avoid Resource Leaks with Try-With-Resources

To make your code more robust (and prevent leftover open streams/connections if an exception occurs), wrap your resources in a try-with-resources block. It automatically closes resources for you:

private static void loadProperties() throws Exception {
    String properties = null;
    // Auto-close connection and reader when block exits
    try (HttpsURLConnection con = (HttpsURLConnection) new URL(getEndpoint()).openConnection();
         BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream(), StandardCharsets.UTF_8))) {
        
        String inputLine;
        StringBuffer res = new StringBuffer();
        while((inputLine = in.readLine()) != null) {
            res.append(inputLine);
        }
        
        JsonObject jsonObject = new JsonParser().parse(res.toString()).getAsJsonObject();
        if(jsonObject.has("error")) {
            JsonObject error = jsonObject.get("error").getAsJsonObject();
            if(error.has("errorCode") && "1000".equals(error.get("errorCode").getAsString()) && jsonObject.has("data")) {
                properties = jsonObject.get("data").getAsJsonArray().toString();
                log("PropertiesUtils.loadProperties: Properties = %s", properties);
                setProperties(properties);
            } else {
                throw new Exception("PropertiesUtils.loadProperties: Error while calling properties endpoint");
            }
        } else {
            throw new Exception("PropertiesUtils.loadProperties: Error while calling properties endpoint");
        }
    }
}

That should resolve the garbled character issue completely. Let me know if you hit any other snags!

内容的提问来源于stack exchange,提问作者user8058277

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 00:32:44