[英]Should I parse JSON once and store the data in an ArrayList for future use OR parse it every time I need the data?
I have a JSON Array that contains JSON Objects.我有一个包含 JSON 对象的 JSON 数组。 Each JSON Object only has a simple
key
/ value
pairs (no nested array or something like that).每个 JSON 对象只有一个简单的
key
/ value
对(没有嵌套数组或类似的东西)。 For example:例如:
[
{
"id": "01",
"name": "Zero One",
"desc": "Something about Zero One"
...
},
...
]
Values in those JSON Objects will be used later by the app.应用程序稍后将使用这些 JSON 对象中的值。
Based on my limited experience, there are two easy ways to accomplish this:根据我有限的经验,有两种简单的方法可以做到这一点:
ArrayList
(or any List
or even a Map
) of POJOs. ArrayList
(或任何List
,甚至是Map
的POJO)。HashMap
or ArrayMap
is probably better for getting/accessing the value, but I read that Map
is even more memory hogging than a simple List
.HashMap
或ArrayMap
可能更适合获取/访问值,但我读到Map
比简单的List
占用更多内存。id
, to get the value
.id
以获取value
。 Which one is better in terms of performance AND memory efficiency ?哪个在性能和内存效率方面更好?
Is there an alternative that's even better than both?有没有比两者都更好的替代方案?
Processing the entire JSON file by loading it into memory can be painful and can crash a lot memory constrained devices.通过将整个 JSON 文件加载到内存中来处理它可能会很痛苦,并且可能会导致很多内存受限的设备崩溃。 However, using the a Jackson JSON parsing library ( https://github.com/FasterXML/jackson ) you can stream the http-request as a Reader into Jacksons Streaming API which will allow you to process each JSON object as soon as it comes down from the pipe.
但是,使用 Jackson JSON 解析库 ( https://github.com/FasterXML/jackson ),您可以将 http-request 作为 Reader 流式传输到 Jacksons Streaming API 中,这将允许您在每个 JSON 对象出现时立即对其进行处理从管道下来。 This allows you to process the data as it comes down the pipe instead of loading the entire JSON file.
这允许您在数据进入管道时对其进行处理,而不是加载整个 JSON 文件。
I use the ObjectMapper from Jackson to deserialize the JSON into a POJO.我使用 Jackson 的 ObjectMapper 将 JSON 反序列化为 POJO。 This allows me to work with domain objects throughout my app, therefore, I don't have to worry about parsing JSON objects all over the place (or cursors if you move the data into a DB locally on the device).
这使我可以在整个应用程序中使用域对象,因此,我不必担心到处解析 JSON 对象(如果将数据移动到设备本地的数据库中,则不必担心游标)。 If you were to load the entire JSON file into the object mapper you'd create a humongous object graph which may ballon your memory out of the bounds of what's available and you might get a OutOfMemoryException.
如果您要将整个 JSON 文件加载到对象映射器中,您将创建一个庞大的对象图,它可能会使您的内存超出可用范围,并且您可能会收到 OutOfMemoryException。 The end goal is to process EACH of the JSON objects as they come down, but also have the benefit of using a POJO to do so.
最终目标是在每个 JSON 对象下降时处理它们,但也有使用 POJO 这样做的好处。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.