我有一个 Android 应用程序必须解析 JSON 文件。最初,我使用内置的 JSON.org 解析器,但单独运行 JSONArray node1=new JSONArray(response);
命令需要大约 30 秒。
我看到有人推荐 jackson ,所以我尝试了一下,这可能会让问题变得更糟。
我的调用 JsonNode rootNode = mapper.readTree(responseString);
大约需要 20 秒。
此外,以下几行还需要大约 10 秒:
ObjectMapper mapper = new ObjectMapper();
TypeReference<List<Dealership>> typeRef = new TypeReference<List<Dealership>>(){};
List<Dealership> dealerships = mapper.readValue(rootNode.traverse(), typeRef);
解析真的需要这么长时间吗?一旦我有了数组,我的代码就会快速运行,直到达到需要花费大量时间的程度。
我可以做些什么来优化我的代码吗?我应该尝试 jackson 以外的东西,还是应该以其他方式使用 jackson ?
最佳答案
您会注意到ObjectMapper#readTree(..)
状态
Method to deserialize JSON content as tree expressed using set of JsonNode instances.
所以这会解析 JSON 一次。
您还会注意到 ObjectMapper#readValue(..)
还指出了
Method to deserialize JSON content into a non-container type (it can be an array type, however): typically a bean, array or a wrapper type (like java.lang.Boolean).
所以你实际上解析了你的 JSON 两次,这可能会减慢你的速度。
直接用
解析一次即可mapper.readValue(responseString, typeRef)
关于java - Jackson 解析 JSON(700 KB 文件)需要 30 秒以上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20832804/