android Gson解析本地SD卡的json文件内存溢出
迷茫
迷茫 2017-04-17 15:53:40
0
5
633

开发时需要从本地的SD卡读取json文件导入数据库,文件有1.3M大小,使用Gson读取时报错内存溢出,这个怎么解决??

迷茫
迷茫

业精于勤,荒于嬉;行成于思,毁于随。

reply all (5)
洪涛

First of all, you didn’t post the specific error message.
As for OOM, for extremely large (although your 1.3M is not called extremely large) json files, usingJson Stringis bound to OOM.
It is recommended to use FastJson, which has a built-in API for processing large json files
https://github.com/alibaba/fastjson/wiki/Stream-api


JSONReader reader = new JSONReader(new FileReader("/tmp/huge.json")); reader.startArray(); while(reader.hasNext()) { VO vo = reader.readObject(VO.class); // handle vo ... } reader.endArray(); reader.close();
JSONReader reader = new JSONReader(new FileReader("/tmp/huge.json")); reader.startObject(); while(reader.hasNext()) { String key = reader.readString(); VO vo = reader.readObject(VO.class); // handle vo ... } reader.endObject(); reader.close();
    Peter_Zhu

    Consider using stream operations for large files, and try not to load the entire string directly. Gson provides JsonReader for file stream operations.

      刘奇

      Gson provides streams, just don’t use String.

      Gson gson = new Gson(); Reader reader = new FileReader("/path/to/file"); YourBean bean = gson.fromJson(reader,YourBean.class);
        刘奇

        Let me post how to report the error first.

        Try using other open source libraries~ If not, parse jsonObject/JsonArray yourself

          洪涛

          I was the fool this time. . .

          Gson assigns values to UserBean in one-to-one correspondence by searching for key. . . .
          So, you must ensure that the Key in the Json data returned in the API is the same as the UserBean.

            Latest Downloads
            More>
            Web Effects
            Website Source Code
            Website Materials
            Front End Template
            About us Disclaimer Sitemap
            php.cn:Public welfare online PHP training,Help PHP learners grow quickly!