java 解析 JsonObject 时出错



我正在为java做一个json解析器。我以字符串形式接收 json,然后尝试获取所有键值

这是我的 Json 字符串

 { "Message":{"field": [ {"bit":2,"name":"AAA"}, {"bit":3,"name":"BBB"}]}}

这是我的解析器:

                JSONObject jObject = new JSONObject(result); //result contains the json                 
                JSONArray info = jObject.getJSONArray("field");
                for (int i = 0 ; i < info.length(); i++) {
                    JSONObject obj = info.getJSONObject(i);
                    Iterator<String> keys = obj.keys();
                    while (keys.hasNext()) { //I use key - value cause the json can change
                        String key =  keys.next();
                        System.out.println("Key: " + key + "tValue: " + obj.get(key));
                    }
                }

但是每次我运行代码时,我都会得到:

Error parsing json org.json.JSONException: JSONObject["field"] not found.

我猜这个领域是一个 JsonArray...我错了吗?

谢谢你的时间

你太深了,想从你的jObject得到field.您需要做的是:

JSONObject jObject = new JSONObject(result);
JSONObject jMsg = jObject.getJSONObject("Message");               
JSONArray info = jMsg.getJSONArray("field");
你需要

JSONObjct Message获取JSONArray field

String result = "{ "Message":{"field": [ {"bit":2,"name":"AAA"}, {"bit":3,"name":"BBB"}]}}";
JSONObject jObject = new JSONObject(result).getJSONObject("Message"); //result contains the json
JSONArray info = jObject.getJSONArray("field");
for (int i = 0 ; i < info.length(); i++) {
    JSONObject obj = info.getJSONObject(i);
    Iterator<String> keys = obj.keys();
    while (keys.hasNext()) { //I use key - value cause the json can change
        String key =  keys.next();
        System.out.println("Key: " + key + "tValue: " + obj.get(key));
    }
}

输出:

Key: name   Value: AAA
Key: bit    Value: 2
Key: name   Value: BBB
Key: bit    Value: 3

试试这个:

        String result = "{ "Message":{"field": [ {"bit":2,"name":"AAA"}, {"bit":3,"name":"BBB"}]}}";
    JSONObject jObject = new JSONObject(result); //result contains the json
    JSONArray info = jObject.getJSONObject("Message").getJSONArray("field");
    for (int i = 0 ; i < info.length(); i++) {
        JSONObject obj = info.getJSONObject(i);
        Iterator<String> keys = obj.keys();
        while (keys.hasNext()) { //I use key - value cause the json can change
            String key =  keys.next();
            System.out.println("Key: " + key + "tValue: " + obj.get(key));
        }
    }

最新更新