我有一个很大的数据流,可以从我使用CharlesProxy玩的游戏中捕捉到。我想要解析数据,并让它打印出来(最终构建一个excel电子表格),播放器名称,x和y位置,以及公会名称。
粘贴-Bin中的JSON数据(您必须从下面的几个条目中看到一个实际返回播放机名称的结果):http://pastebin.com/v4kAaspn
下面是我在这里发现的一个示例,我试图使用它来返回播放器名,但是我得到了一个Null指针异常错误。任何建议都将不胜感激,非常感谢!
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class ToolMain {
public static void main(String[] args) {
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(new FileReader(
"//Users//Brandon//Desktop//JSONData.JSON"));
JSONObject jsonObject = (JSONObject) obj;
//get responses
JSONArray rsp = (JSONArray)jsonObject.get("responses");
//System.out.println(rsp);
//get return value
JSONObject rtvalue = (JSONObject)rsp.get(0);
//System.out.println(rtvalue);
//get hexes object
JSONObject hexes = (JSONObject)rtvalue.get("return_value");
//System.out.println(hexes);
//get hexes array
JSONArray hexesArray = (JSONArray)hexes.get("hexes");
Iterator<JSONObject> iterator = hexesArray.iterator();
while (iterator.hasNext()) {
JSONObject factObj = iterator.next();
String playerName = (String) factObj.get("player_name");
if (playerName != null) {
System.out.println(playerName);
}
}
//System.out.println(hexesArray);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
}发布于 2015-04-04 14:10:53
NullPointerException发生在下面一行,因为您的JSONArray msg是空的:
Iterator<JSONObject> iterator = msg.iterator();在创建迭代器之前应用检查(msg不是null)。
这样试一试:
JSONObject jsonObject = (JSONObject) obj;
//get responses
JSONArray rsp = (JSONArray)jsonObject.get("responses");
System.out.println(rsp);
//get return value
JSONObject rtvalue = (JSONObject)rsp.get(0);
System.out.println(rtvalue);
//get hexes object
JSONObject hexes = (JSONObject)rtvalue.get("return_value");
System.out.println(hexes);
//get hexes array
JSONArray hexesArray = (JSONArray)hexes.get("hexes");
System.out.println(hexesArray);https://stackoverflow.com/questions/29447266
复制相似问题