繁体   English   中英

在Android中进行JSON解析时OutOfMemoryError

[英]OutOfMemoryError while JSON parsing in android

我使用下面的代码来解析从Web获取的JSON字符串,(30,000条记录)

DefaultHttpClient   httpclient = new DefaultHttpClient(new BasicHttpParams());
        HttpPost httppost = new HttpPost(params[0]);
        httppost.setHeader("Content-type", "application/json");
        InputStream inputStream = null;
        String result = null;
        HttpResponse response = null;
        try {
            response = httpclient.execute(httppost);

        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }           
        HttpEntity entity = response.getEntity();
        try {
            inputStream = entity.getContent();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"),8);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        StringBuilder sb = new StringBuilder();
        String line = null;
        try {
            while ((line = reader.readLine()) != null)  
            {
                sb.append(line + "\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        result = sb.toString();

我在下面的代码中收到OutofMemory错误

while ((line = reader.readLine()) != null)  
{
    sb.append(line + "\n");
}

如何摆脱这个错误。当json字符串非常庞大时,会发生此错误,因为它包含大约30,000条记录的数据。

在这方面的任何帮助都非常感谢..

Android为每个应用程序设置了内存上限(几乎所有手机中都有16 MB,而一些新的平板电脑有更多)。 应用程序应确保它们的实时内存限制保持在该级别以下。

因此,我们不能保持一个大字符串,比如超过1MB,因为应用程序的总活动内存使用量可能会超过该限制。 请记住,总内存使用量包括我们在应用程序中分配的所有对象(包括UI元素)。

因此,您唯一的解决方案是使用Streaming JSON解析器,它可以获取数据。 那就是你不应该在String对象中保持完整的字符串。 一种选择是使用Jackson JSON解析器

编辑:Android现在支持API级别11的JSONReader 。从未使用它,但它似乎要走了......

如果数据文件太大,则无法将其全部读取到内存中。

读取一行,然后将其写入本机文件。 不要使用StringBuilder来保存内存中的所有数据。

尝试在chuncks中导入数据,例如每次1000条记录。 希望你不会遇到这个问题。

我用这个解决了这个问题。 有一个很好的教程在这里

有了这个,你将绕过将entity.getContent()转换为String,这将解决你的问题。

InputStream inputStream = entity.getContent();
JsonReader reader = Json.createReader(inputStream);
JsonObject jsonObject = reader.readObject();
return jsonObject;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM