Android应用程序中JSON对象绑定的替代方法

时间:2014-10-31 17:51:09

标签: java android json parsing gson

从我的Android应用程序中,我需要使用RESTful Web服务,它以json格式返回一个对象列表。 这个列表可能很长(约1000/2000对象)。

我需要做的是搜索和检索json文件中的一些对象。

由于移动设备的内存有限,我认为使用对象绑定(例如使用GSON库)可能很危险。

解决这个问题的替代方法是什么?

2 个答案:

答案 0 :(得分:1)

If you are using gson, use gson streaming

我已从链接中添加了示例,并在其中添加了我的评论:

public List<Message> readJsonStream(InputStream in) throws IOException {
    JsonReader reader = new JsonReader(new InputStreamReader(in, "UTF-8"));
    List<Message> messages = new ArrayList<Message>();
    reader.beginArray();
    while (reader.hasNext()) {
        Message message = gson.fromJson(reader, Message.class);
        // TODO : write an if statement
        if(someCase) {
            messages.add(message);
            // if you want to use less memory, don't add the objects into an array. 
            // write them to the disk (i.e. use sql lite, shared preferences or a file...) and
            // and retrieve them when you need.
        }
    }
    reader.endArray();
    reader.close();
    return messages;
}

答案 1 :(得分:0)

例如

1)将列表作为流读取并动态处理单个JSON实体并仅保存您感兴趣的实体

2)将数据读入String对象/对象,然后找到JSON实体并逐个处理它们而不是同时处理所有实体。分析JSON结构的字符串的方法包括正则表达式或手动indexOf以及子字符串类型分析。

1)效率更高但需要更多的工作,因为你必须同时处理流,因为2)可能更简单,但它要求你使用相当大的字符串作为临时手段。