首页 > 解决方案 > 文件已存在时的 IO 异常 - Gson Android

问题描述

我正在尝试解析一个名为“category.json”的本地 json 文件,但是当我调用该文件时,我得到一个“未处理的 IO 异常”错误。我也创建了 category.json 文件。

public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View rootView= inflater.inflate(R.layout.content_menu, container, false);

    String jsonArray="category.json";
    Gson gson = new Gson();
    List<Category> list = gson.fromJson(new FileReader(jsonArray), new TypeToken<List<Category>>(){}.getType());


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

    return rootView;
}

我什至尝试使用 AssetManager 我仍然得到同样的错误

    AssetManager assetManager =getContext().getAssets();
    InputStream is = assetManager.open("category.json");

标签: androidexception-handlinggson

解决方案


您必须按如下方式处理IOException使用 a ,try - catch

try {
    AssetManager assetManager = getContext().getAssets();
    InputStream is = assetManager.open("category.json");

    // do something with your stream

} catch (IOException e) {
    e.printStackTrace();
}

在此处阅读有关异常处理的更多信息。

类似的线程在这里


推荐阅读