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

Android Studio读取JSON文件时模拟器打印结果异常求助

解决Android Studio读取JSON文件无准确输出的问题

看你提供的代码片段,核心是通过HttpHandler发起网络请求获取JSON,但模拟器上没拿到预期结果。咱们一步步拆解问题、排查解决:

可能的问题点及对应方案

1. 网络权限与明文请求限制没配置对

Android对网络请求有严格的权限和安全限制,这是最容易踩的坑:

  • 先在AndroidManifest.xml里添加必要权限:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
  • 如果你的请求URL是http而非https,需要配置允许明文流量:
    在res/xml目录下创建network_security_config.xml,内容如下:
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <base-config cleartextTrafficPermitted="true" />
</network-security-config>

然后在Manifest的<application>标签里引用这个配置:

android:networkSecurityConfig="@xml/network_security_config"

2. 自定义HttpHandler的请求逻辑有问题

你用的HttpHandler是自己写的工具类吧?大概率是makeServiceCall方法里的逻辑有漏洞,比如没处理异常、读取响应流出错、编码不对。给你一个靠谱的实现参考:

public class HttpHandler {
    private static final String TAG = HttpHandler.class.getSimpleName();

    public String makeServiceCall(String reqUrl) {
        String response = null;
        try {
            URL url = new URL(reqUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            // 设置超时时间,避免无限等待
            conn.setConnectTimeout(5000);
            conn.setReadTimeout(5000);
            
            // 读取响应流
            InputStream in = new BufferedInputStream(conn.getInputStream());
            response = convertStreamToString(in);
        } catch (MalformedURLException e) {
            Log.e(TAG, "URL格式错误: " + e.getMessage());
        } catch (IOException e) {
            Log.e(TAG, "网络IO异常: " + e.getMessage());
        } catch (Exception e) {
            Log.e(TAG, "其他异常: " + e.getMessage());
        }
        return response;
    }

    private String convertStreamToString(InputStream is) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();
        String line;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }
}

3. JSON解析逻辑不完整或异常未处理

你的代码只写到获取games数组,后续如果解析出错也会导致无输出。补全解析逻辑并加上异常捕获:

@Override
protected Void doInBackground(Void... arg0) {
    HttpHandler sh = new HttpHandler();
    String jsonStr = sh.makeServiceCall(url);
    Log.e(TAG, "Response from url: " + jsonStr);

    if (jsonStr != null) {
        try {
            JSONObject jsonObj = new JSONObject(jsonStr);
            JSONArray games = jsonObj.getJSONArray("games");
            
            // 遍历数组,解析每个游戏对象
            for (int i = 0; i < games.length(); i++) {
                JSONObject gameObj = games.getJSONObject(i);
                // 替换成你JSON里的实际字段名
                String gameId = gameObj.getString("id");
                String gameName = gameObj.getString("name");
                String gameGenre = gameObj.getString("genre");
                
                // 打印解析结果
                Log.e(TAG, "游戏" + (i+1) + ": ID=" + gameId + ", 名称=" + gameName + ", 类型=" + gameGenre);
            }
        } catch (JSONException e) {
            Log.e(TAG, "JSON解析失败: " + e.getMessage());
            e.printStackTrace();
        }
    }
    return null;
}

注意要确保你获取的字段名和JSON里的完全一致,大小写、拼写都不能错。

4. 模拟器网络本身有问题

模拟器的网络有时候会和主机不同步:

  • 检查模拟器状态栏的网络标识,确认已联网
  • 如果是访问本地服务器的JSON文件,模拟器里要写10.0.2.2(对应主机的localhost),不能直接用localhost或主机的实际IP
  • 试试重启模拟器,或者切换模拟器的网络模式(比如从Wi-Fi切到蜂窝网络)

调试小技巧

  • 先看Log里的Response from url:输出,如果是null或乱码,先解决网络请求问题;如果是正确的JSON字符串,再排查解析逻辑
  • 把jsonStr完整打印出来,复制到JSON在线解析工具里验证是否是合法的JSON格式

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 03:23:01