简体   繁体   English

打印键值无法与JSONObject一起正常工作

[英]print key values not working as expected with JSONObject

I'm trying to print out all the key values in the JSON below but for whatever reason its only printing the first set array of values for me. 我正在尝试打印出下面JSON中的所有键值,但是出于某种原因,它只为我打印了第一组值。

How can i make it that all the key values in the idValue String are printed out? 我如何才能确保将idValue字符串中的所有键值都打印出来?

Edit: I'm now getting the error: 编辑:我现在得到错误:

Unexpected Error : JSONObject["submenu"] not a string. 意外错误:JSONObject [“ submenu”]不是字符串。

Code

import com.google.common.collect.LinkedListMultimap;
import com.google.common.collect.Multimap;
import org.json.JSONArray;
import org.json.JSONObject;

import java.util.Map;

public class testing {
    static Multimap<String, String> allMappedKeyValues = LinkedListMultimap.create();

    public static void main(String[] args) {

        String idValue = "[{\"link\": \"/us_new/en/home\",\"amid\": \"1__home\",\"title\": \"Home\"}, {\"link\": \"/us_new/en/home/diagnosis\",\"amid\": \"2__diagnosis\",\"title\": \"Diagnosis\"}, {\"link\": \"/us_new/en/home/loss\",\"amid\": \"3__loss\",\"title\": \"loss\",\"submenu\": [{\"amid\": \"4__quiz\",\"name\": \"quiz\",\"title\": \"quiz\"},{\"amid\": \"5__questions\",\"name\": \"questions\",\"title\": \"Questions\"}]}]";

        JSONArray array = new JSONArray(idValue);
        for (int i = 0; i < array.length(); i++)
        {
            JSONObject object = array.getJSONObject(i);
            JSONArray keys = object.names();

            for (int j = 0; j < keys.length(); ++j)
            {
                String key = keys.getString(j);
                Object value = object.get(key);

                if (value instanceof JSONArray) {

                    JSONArray array1 = (JSONArray) value;

                    for (int k = 0; k < array1.length(); k++) {
                        JSONObject object1 = array1.getJSONObject(k);

                        JSONArray keys1 = object1.names();

                        String key2 = keys1.getString(k);
                        String value2 = object1.getString(key2);
                        String title2 = object1.getString("title");
//                        System.out.println("-key :" + key2 + "\n-value " + value2 + "\n-title :" + title2);

                        if (key2.contains("amid")) {
                            allMappedKeyValues.put(value2 + "__title", title2);
                        }
                    }
                } else {
                    String key1 = keys.getString(j);
                    String value1 = object.getString(key1);
                    String title1 = object.getString("title");
//                    System.out.println("-key :" + key1 + "\n-value " + value1 + "\n-title :" + title1);

                    if (key.equals("amid")) {
                        allMappedKeyValues.put(value1 + "__title", title1);
                    }
                }
            }
        }

        for (Map.Entry<String, String> entry : allMappedKeyValues.entries()) {
            System.out.println("This is the key-" + entry.getKey() + " value-" + entry.getValue());
        }
    }
}

JSON JSON格式

[{"link": "/us_new/en/home","amid": "1__home","title": "Home"}, {"link": "/us_new/en/home/diagnosis","amid": "2__diagnosis","title": "Diagnosis"}, {"link": "/us_new/en/home/loss","amid": "3__loss","title": "loss","submenu": [{"amid": "4__quiz","name": "quiz","title": "quiz"},{"amid": "5__questions","name": "questions","title": "Questions"}]}]

Output 输出量

  Entered loop :0
-key :link
-value /us_new/en/home
-title :Home
Entered loop :1
-key :amid
-value 1__home
-title :Home
Entered loop :2
-key :title
-value Home
-title :Home

You don't need to replace [] , your JSON is in correct format. 您不需要替换[] ,您的JSON格式正确。 You can actually create JSONArray directly from the String, 实际上,您可以直接从String创建JSONArray

String idValue = "[{\"link\":\"/us_new/en/home\",\"amid\":\"1__home\",\"title\":\"Home\"},{\"link\":\"/us_new/en/home/diagnosis\",\"amid\":\"2__diagnosis\",\"title\":\"Diagnosis\"},{\"link\":\"/us_new/en/home/treatment\",\"amid\":\"3__loss\",\"title\":\"loss\"}]";
JSONArray objects = new JSONArray(idValue);
for(int i = 0; i < objects.length(); i++) {
    JSONObject jsonObject = objects.getJSONObject(i);

    Iterator<String> keys = jsonObject.keys();
    while(keys.hasNext()) {
        String key = keys.next();
        System.out.printf("key : %s | value : %s\n", key, jsonObject.get(key));
    }
}

Output : 输出:

key : link | value : /us_new/en/home
key : amid | value : 1__home
key : title | value : Home
key : link | value : /us_new/en/home/diagnosis
key : amid | value : 2__diagnosis
key : title | value : Diagnosis
key : link | value : /us_new/en/home/treatment
key : amid | value : 3__loss
key : title | value : loss

you can use following recursive function "parseJsonArray" to parse your nested jsonArrays. 您可以使用以下递归函数“ parseJsonArray”来解析嵌套的jsonArray。

String idValue = "[{\"link\": \"/us_new/en/home\",\"amid\": \"1__home\",\"title\": \"Home\"}, {\"link\": \"/us_new/en/home/diagnosis\",\"amid\": \"2__diagnosis\",\"title\": \"Diagnosis\"}, {\"link\": \"/us_new/en/home/loss\",\"amid\": \"3__loss\",\"title\": \"loss\",\"submenu\": [{\"amid\": \"4__quiz\",\"name\": \"quiz\",\"title\": \"quiz\"},{\"amid\": \"5__questions\",\"name\": \"questions\",\"title\": \"Questions\"}]}]";

parseJsonArray(idValue);

private void parseJsonArray(String jsonString) throws JSONException {
    System.out.println("jsonString: " + jsonString);

    JSONArray objects = new JSONArray(jsonString);
    JSONArray  nestedJsonArray;
    JSONObject  nestedJsonObject;

    for(int i = 0; i < objects.length(); i++) {
        JSONObject jsonObject = objects.getJSONObject(i);
        Iterator<String> keys = jsonObject.keys();

        while(keys.hasNext()) {
            String key = keys.next();                
            Object nestedObject = jsonObject.get(key);
            if (nestedObject instanceof JSONArray) {
                System.out.println("it's an array: " + key);
                nestedJsonArray = (JSONArray)nestedObject;
                parseJsonArray(nestedJsonArray.toString());
            }
            else if (nestedObject instanceof JSONObject) {
                nestedJsonObject = (JSONObject)nestedObject;
                System.out.printf("key : %s | value : %s | title : %s\n", key, nestedJsonObject.getString(key), nestedJsonObject.getString("title"));
            }
            else {
                System.out.printf("key : %s | value : %s | title : %s\n", key, jsonObject.getString(key), jsonObject.getString("title"));
            }
        }
    }

You only read the first JSON object ( {\\"link\\":\\"/us_new/en/home\\",\\"amid\\":\\"1__home\\",\\"title\\":\\"Home\\"} ). 您仅读取第一个JSON对象( {\\"link\\":\\"/us_new/en/home\\",\\"amid\\":\\"1__home\\",\\"title\\":\\"Home\\"} )。 In order to read all 3 objects, first change the JSON String to an array (add the missing [ and ] ): 为了读取所有3个对象,首先将JSON字符串更改为一个数组(添加缺少的[] ):

String idValue = "[{\"link\":\"/us_new/en/home\",\"amid\":\"1__home\",\"title\":\"Home\"},{\"link\":\"/us_new/en/home/diagnosis\",\"amid\":\"2__diagnosis\",\"title\":\"Diagnosis\"},{\"link\":\"/us_new/en/home/treatment\",\"amid\":\"3__loss\",\"title\":\"loss\"}]";

Then iterate over the array: 然后遍历数组:

JSONArray array = new JSONArray(idValue);
for (int i = 0; i < array.length (); i++) {
    JSONObject object = array.getJSONObject (i);
    JSONArray keys = object.names();
    for (int j = 0; j < keys.length(); ++j) {
        System.out.println("Entered loop :"+j);
        String key = keys.getString(j);
        String value = object.getString(key);
        String title = object.getString("title");
        System.out.println("-key :" + key + "\n-value " + value + "\n-title :" + title);
    }
}

Output: 输出:

Entered loop :0
-key :link
-value /us_new/en/home
-title :Home
Entered loop :1
-key :amid
-value 1__home
-title :Home
Entered loop :2
-key :title
-value Home
-title :Home
Entered loop :0
-key :link
-value /us_new/en/home/diagnosis
-title :Diagnosis
Entered loop :1
-key :amid
-value 2__diagnosis
-title :Diagnosis
Entered loop :2
-key :title
-value Diagnosis
-title :Diagnosis
Entered loop :0
-key :link
-value /us_new/en/home/treatment
-title :loss
Entered loop :1
-key :amid
-value 3__loss
-title :loss
Entered loop :2
-key :title
-value loss
-title :loss

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

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