繁体   English   中英

用Java选择性地解析JSON

[英]Selectively parse JSON in Java

我有一个像这样的JSON文件:

{"start":1489730400000, 
"end":1489733999999, 
"interval":1000, 
"weight":1, 
"augmented": true, 
"profileName":"Selene/prod", 
"prunedSamples":0, 
"fleet":{"c4.2xlarge":14.313278698132972}, "costPerSecond":0.000008259246540496541, 
"profileData":{
    "name":"ALL", 
    "states":{"BLOCKED":2281, "NEW":0, "RUNNABLE":125833, "TERMINATED":0, "TIMED_WAITING":23170429, "WAITING":59901416},
    "location": "0", 
    "hidden": [], 
    "children":[{"name":"GarbageCollector.gc", 
    "states":{"BLOCKED":0, "NEW":0, "RUNNABLE":17069}, 
    "location": "0.0", 
    "hidden": [], 
    "children":[{"name":"ConcurrentMarkSweep.gc", 
                "states":{"BLOCKED":0, "NEW":0, "RUNNABLE":14977}, 
                "location": "0.0.0", 
                "hidden": [], 
                "level": 1},
                {"name":"ParNew.gc", 
                 "states":{"BLOCKED":0, "NEW":0, "RUNNABLE":2092}, 
                 "location": "0.0.1", 
                 "hidden": [], 
                 "level": 1}]
}}

这只是其中的一部分。 我得到了一个更大的GZip格式文件,我先对其进行解压缩并将解压缩的部分存储在字符串中。 我为此使用以下代码:

URL url = new URL("http://example.com/Selene%20Prod?start=1490234400000&end=1490237999999&maxDepth=200&minimumCountsThreshold=0.00");
URLConnection myUrlConnection = url.openConnection();
GZIPInputStream gZIPInputStream = new GZIPInputStream(myUrlConnection.getInputStream());
StringBuffer decompressedStringBuffer = new StringBuffer();
int bytes_read;
while ((bytes_read = gZIPInputStream.read(buffer)) > 0) {
    String part = new String(buffer, 0 ,bytes_read, "UTF-8");
    decompressedStringBuffer.append(part);
}
gZIPInputStream.close();
String decompressedString = decompressedStringBuffer.toString();
JSONObject obj = new JSONObject(decompressedString);
JSONArray profileData = obj.getJSONObject("profileData").getJSONArray("children");

我的代码给出Caused by: java.lang.OutOfMemoryError: Java heap space decompressedStringBuffer.append(part);上的Caused by: java.lang.OutOfMemoryError: Java heap space decompressedStringBuffer.append(part); 由于文件太大而无法存储在内存中,因此我考虑过将其存储在文件中,然后读回该文件以转换为JSON,但是随后我将使用FileInputStream创建的JSON对象将给我一个Caused by:java.lang.OutOfMemoryError: Java heap space

我得到的JSON中唯一有用的数据是profileData键下的namechildren

有没有一种方法只能在解析inputStream时将它们转换为JSONObject并忽略其他对象?

如果有更好的方法,有人可以想到,我也将不胜感激。

我认为您不必去JACKSON库,只需尝试找到一种仅在GSON中解析大型JSON的方法。

尝试使用此资源,这是GSON作者的答案。 在同一页面上,您还将找到使用流和树模型的JACKSON的工作示例(以防您继续使用Jackson的情况)

另外,如果您想增加堆大小,请参考下面的链接: 如何增加Java堆大小

暂无
暂无

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

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