我在名为JacksonStreamExample的Java类中使用json-simple库解析以下http://pastebin.com/Mb5E6Ewf文件。
在这个JSON文件中,我有一个JSON对象,里面有一个由6个JSON对象组成的数组,结构如下:
{"cells": [{object with name START},{object with name END},{object with name ACTIVITY 1},{object with name ACTIVITY 2},{object with name link},{object with name link}]}我想在这6个JSON对象中搜索wi_name:START,并获取这个特定JSON对象的wi_displayName,但是到目前为止,在我的代码中,我只能在一个迭代器中获得这6个JSON对象的所有wi_name键。你能告诉我如何修复我的代码吗?
这是我的Java类的代码:
package jsontoxml;
import java.io.*;
import org.json.simple.parser.JSONParser;
import org.json.simple.*;
import java.util.*;
public class JacksonStreamExample {
public static void main(String[] args) {
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(new FileReader("text.json"));
JSONObject jsonObject = (JSONObject) obj;
JSONArray cells = (JSONArray) jsonObject.get("cells");
Iterator<JSONObject> iterator = cells.iterator();
while(iterator.hasNext()){
System.out.println(iterator.next().get("wi_name"));
}
} catch (Exception e) {
e.printStackTrace();
}
}
}输出结果如下:
START
END
ACTIVITY_1
ACTIVITY_2
null
null发布于 2017-01-16 20:56:39
我通过这样修改代码解决了我的问题:
while(iterator.hasNext()){
JSONObject jsonObject2 = (JSONObject) iterator.next();
if(jsonObject2.get("wi_name").equals("START")){
System.out.println(jsonObject2.get("wi_displayName"));
}
}发布于 2017-01-16 06:56:16
使用JSON遍历org.json通常有点麻烦,因为它缺乏所有舒适的特性,但现在开始:
while(iterator.hasNext()){
JSONobject current = iterator.next();
if(current.get("wi_name") != null && current.get("wi_name").equals("START")) {
// maybe do some null- and/or empty-checks here or what ever you want with the data
System.out.println(current.get("wi_displayName"));
};
}希望这能有所帮助!
https://stackoverflow.com/questions/41666891
复制相似问题