如何解析大型本地JSON文件以使用数组检索播放器名称等

时间:2015-04-04 13:58:23

标签: java json parsing packet

我有一大堆数据可以从我使用CharlesProxy玩的游戏中捕获。我想解析数据并打印出来(最终建立一个excel电子表格)玩家名称,x和y位置以及公会名称。

粘贴框中的JSON数据(您必须查看几个条目以查看实际返回玩家名称的结果之一): http://pastebin.com/v4kAaspn

这是我在这里找到的一个例子,我试图用它来返回播放器名称,但是我得到一个空指针异常错误。非常感谢任何建议,非常感谢你!

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();
        }

    }

}

1 个答案:

答案 0 :(得分:0)

NullPointerException发生在下面的行,因为你的JSONArray msg为null:

Iterator<JSONObject> iterator = msg.iterator();

在创建迭代器之前应用检查if(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);