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

Android中Gson解析本地JSON文件遇未处理IO异常(文件已存在)

解决Android读取本地JSON文件的Unhandled IO Exception问题

咱们一步步来排查这个问题的根源:

  • 你第一次用FileReader("category.json")时踩了个常见坑:Android的FileReader默认会去设备系统根目录找文件,但你的category.json大概率是放在项目的assets文件夹里的,根目录根本不存在这个文件,自然抛出IO异常。
  • 后来尝试AssetManager的方向是对的,但你只写了打开流的代码,既没处理IO异常,也没完成读取文件内容、解析成对象的完整流程,所以错误依旧存在。

正确的实现方案

  1. 先确认你的category.json确实放在app/src/main/assets目录下(如果没有assets文件夹,手动创建一个,注意是小写的assets,别拼错)。
  2. 用AssetManager读取文件流,把流转换成字符串后再用Gson解析,同时必须捕获IO异常(Android不允许未处理的检查型异常)。

下面是完整的修正代码:

public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.content_menu, container, false);
    List<Category> list = new ArrayList<>();
    Gson gson = new Gson();

    // 读取assets中的JSON文件
    try {
        AssetManager assetManager = getContext().getAssets();
        InputStream is = assetManager.open("category.json");
        // 将输入流转换为字符串
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
        // 解析JSON字符串为List<Category>
        list = gson.fromJson(sb.toString(), new TypeToken<List<Category>>() {}.getType());
        
        // 关闭流资源
        is.close();
        reader.close();
    } catch (IOException e) {
        // 处理异常:打印日志或提示用户
        e.printStackTrace();
        Toast.makeText(getContext(), "数据加载失败", Toast.LENGTH_SHORT).show();
    }

    // 初始化RecyclerView
    RecyclerView myrv = rootView.findViewById(R.id.recyclerview_id);
    RecyclerViewAdapter myAdapter = new RecyclerViewAdapter(getActivity(), list);
    myrv.setLayoutManager(new GridLayoutManager(getContext(), 3));
    myrv.setAdapter(myAdapter);

    return rootView;
}

额外需要注意的细节

  • 检查category.json的文件名是否完全匹配(Android对文件名大小写敏感,比如Category.json和category.json会被识别为两个不同文件)。
  • 确保JSON文件格式正确,格式错误会导致解析失败(可以用在线JSON校验工具检查)。
  • 永远不要忽略IO异常的捕获,未处理的检查型异常也是你之前报错的核心原因之一。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 09:31:07