如何在嵌套的JSON结果中解析动态JSON键?

59

我有一个JSON结果,它的格式如下,JSON Lint 显示为“有效响应”。

我的问题是:如何访问 “question_mark” 的内容,因为 “141”、“8911”等都是动态值?

我用于访问 “product” 值的示例代码。

//Consider I have the first <code>JSONObject</code> of the "search_result" array and 
//I access it's "product" value as below.
String product = jsonObject.optString("product"); //where jsonObject is of type JSONObject.
//<code>product<code> now contains "abc".

JSON:

{
 "status": "OK",
 "search_result": [

            {
                "product": "abc",
                "id": "1132",
                "question_mark": {
                    "141": {
                        "count": "141",
                        "more_description": "this is abc",
                        "seq": "2"
                    },
                    "8911": {
                        "count": "8911",
                        "more_desc": "this is cup",
                        "seq": "1"
                    }
                },
                "name": "some name",
                "description": "This is some product"
            },
            {
                "product": "XYZ",
                "id": "1129",
                "question_mark": {
                    "379": {
                        "count": "379",
                        "more_desc": "this is xyz",
                        "seq": "5"
                    },
                    "845": {
                        "count": "845",
                        "more_desc": "this is table",
                        "seq": "6"
                    },
                    "12383": {
                        "count": "12383",
                        "more_desc": "Jumbo",
                        "seq": "4"
                    },
                    "257258": {
                        "count": "257258",
                        "more_desc": "large",
                        "seq": "1"
                    }
                },
                "name": "some other name",
                "description": "this is some other product"
            }
       ]
}

我提出的问题标题“动态键”可能不正确,但我现在不知道这个问题的更好名称。

非常感谢任何帮助!


在执行之前,我认为你应该拥有问号内对象的值。你有吗? - Lalit Poptani
嗯,不行。我不知道如何访问问号内的值。为此,我必须执行jsonObj.optJSONObject("141"),其中141是动态的,我事先不知道它。 - Sagar Hatekar
5个回答

123

使用JSONObject keys()方法获取键,然后迭代每个键以获取动态值。

大致代码如下:


// searchResult refers to the current element in the array "search_result" but whats searchResult?
JSONObject questionMark = searchResult.getJSONObject("question_mark");
Iterator keys = questionMark.keys();
    
while(keys.hasNext()) {
    // loop to get the dynamic key
    String currentDynamicKey = (String)keys.next();
        
    // get the value of the dynamic key
    JSONObject currentDynamicValue = questionMark.getJSONObject(currentDynamicKey);
        
        // do something here with the value...
}

2
很高兴能够帮助你 :) 如果有任何问题,请随时告诉我。我们(SO社区)都在这里乐意提供帮助。 - momo
我曾经使用过你的代码,现在又来了一次,为你点赞 momo。 - Illegal Argument
它为我增加了解析动态键数组的新知识,节省了我的时间,谢谢。 - sujith s
嗨momo,谢谢你的回答。但是我无法使用上述解决方案,因为我正在使用retrofit,并通过在线工具生成器创建POJO类,该生成器为动态值生成类。这是无用的。你能否建议我如何实现你的最佳解决方案来解决我的问题? - Deepak Sharma
嗨momo,谢谢你的回答。 - akshay bhange
显示剩余2条评论

14

另一种可能性是使用 Gson (注意,我在这里使用 lombok 生成getter/setter、toString等):

package so7304002;

import java.util.List;
import java.util.Map;

import lombok.AccessLevel;
import lombok.Data;
import lombok.NoArgsConstructor;

import com.google.gson.Gson;
import com.google.gson.annotations.SerializedName;
import com.google.gson.reflect.TypeToken;

@NoArgsConstructor(access = AccessLevel.PRIVATE)
public final class JsonDemo {
    @Data
    private static class MyMap {
        private int count;

        @SerializedName("more_description")
        private String moreDescription;

        private int seq;
    }

    @Data
    private static class Product {
        private String product;

        private int id;

        @SerializedName("question_mark")
        private Map<String, MyMap> questionMark;
    }

    @Data
    private static class MyObject {
        private String status;

        @SerializedName("search_result")
        private List<Product> searchResult;
    }

    private static final String INPUT = ""; // your JSON

    public static void main(final String[] arg) {
        final MyObject fromJson = new Gson().fromJson(INPUT, 
            new TypeToken<MyObject>(){}.getType());
        final List<Product> searchResult = fromJson.getSearchResult();
        for (final Product p : searchResult) {
            System.out.println("product: " + p.getProduct() 
                + "\n" + p.getQuestionMark()+ "\n");
        }
    }
}

输出:

product: abc
{141=JsonDemo.MyMap(count=141, moreDescription=this is abc, seq=2), 
 8911=JsonDemo.MyMap(count=8911, moreDescription=null, seq=1)}

product: XYZ
{379=JsonDemo.MyMap(count=379, moreDescription=null, seq=5), 
 845=JsonDemo.MyMap(count=845, moreDescription=null, seq=6), 
 12383=JsonDemo.MyMap(count=12383, moreDescription=null, seq=4), 
 257258=JsonDemo.MyMap(count=257258, moreDescription=null, seq=1)}

感谢您提供有关GSON和RC的有用信息和教程,以及为创建完整的代码示例所做的额外努力。这对其他人来说也将非常有帮助。+1 - Sagar Hatekar
你怎么从Retrofit响应中调用它,而新的Gson().fromJson对我不起作用。 - hossam scott

1

一个使用Google Gson的例子

来自问题的JSON数据:

{
    "status": "OK",
    "search_result": [
        {
            "product": "abc",
            "id": "1132",
            "question_mark": {
                "141": {
                    "count": "141",
                    "more_description": "this is abc",
                    "seq": "2"
                },
                "8911": {
                    "count": "8911",
                    "more_desc": "this is cup",
                    "seq": "1"
                }
            },
            "name": "some name",
            "description": "This is some product"
        },
        {
            "product": "XYZ",
            "id": "1129",
            "question_mark": {
                "379": {
                    "count": "379",
                    "more_desc": "this is xyz",
                    "seq": "5"
                },
                "845": {
                    "count": "845",
                    "more_desc": "this is table",
                    "seq": "6"
                },
                "12383": {
                    "count": "12383",
                    "more_desc": "Jumbo",
                    "seq": "4"
                },
                "257258": {
                    "count": "257258",
                    "more_desc": "large",
                    "seq": "1"
                }
            },
            "name": "some other name",
            "description": "this is some other product"
        }
    ]
}

示例代码:

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;

public class GsonExercise {
    public static void main(String[] args) {
        String jsonString = "{\"status\":\"OK\",\"search_result\":[{\"product\":\"abc\",\"id\":\"1132\",\"question_mark\":{\"141\":{\"count\":\"141\",\"more_description\":\"this is abc\",\"seq\":\"2\"},\"8911\":{\"count\":\"8911\",\"more_desc\":\"this is cup\",\"seq\":\"1\"}},\"name\":\"some name\",\"description\":\"This is some product\"},{\"product\":\"XYZ\",\"id\":\"1129\",\"question_mark\":{\"379\":{\"count\":\"379\",\"more_desc\":\"this is xyz\",\"seq\":\"5\"},\"845\":{\"count\":\"845\",\"more_desc\":\"this is table\",\"seq\":\"6\"},\"12383\":{\"count\":\"12383\",\"more_desc\":\"Jumbo\",\"seq\":\"4\"},\"257258\":{\"count\":\"257258\",\"more_desc\":\"large\",\"seq\":\"1\"}},\"name\":\"some other name\",\"description\":\"this is some other product\"}]}";
        JsonObject jobj = new Gson().fromJson(jsonString, JsonObject.class);
        JsonArray ja = jobj.get("search_result").getAsJsonArray();
        ja.forEach(el -> {
            System.out.println("product: " + el.getAsJsonObject().get("product").getAsString());
            JsonObject jo = el.getAsJsonObject().get("question_mark").getAsJsonObject();            
            jo.entrySet().stream().forEach(qm -> {
                String key = qm.getKey();
                JsonElement je = qm.getValue();
                System.out.println("key: " + key);
                JsonObject o = je.getAsJsonObject();
                o.entrySet().stream().forEach(prop -> {
                    System.out.println("\tname: " + prop.getKey() + " (value: " + prop.getValue().getAsString() + ")");
                });
            });
            System.out.println("");
        });
    } 
}

输出:

product: abc
key: 141
    name: count (value: 141)
    name: more_description (value: this is abc)
    name: seq (value: 2)
key: 8911
    name: count (value: 8911)
    name: more_desc (value: this is cup)
    name: seq (value: 1)

product: XYZ
key: 379
    name: count (value: 379)
    name: more_desc (value: this is xyz)
    name: seq (value: 5)
key: 845
    name: count (value: 845)
    name: more_desc (value: this is table)
    name: seq (value: 6)
key: 12383
    name: count (value: 12383)
    name: more_desc (value: Jumbo)
    name: seq (value: 4)
key: 257258
    name: count (value: 257258)
    name: more_desc (value: large)
    name: seq (value: 1)

以上所有答案都可用于包含数组和json对象的响应,如果响应不是json数组,但与此线程中发布的相同类型的响应,则如何获取问号内的值,类似的问题已经在此处发布,请指导。https://stackoverflow.com/questions/63639243/fetch-the-jsonobject-value-to-a-variable-which-is-inside-the-dynamically-generat - la1

0
你可以使用这个逻辑。使用 org.json 库。
<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20211205</version>
</dependency>


public void parseJson(JSONObject jo, String key) {
Iterator<?> keyIterator;
String key1;
if (jo.has(key)) {
    System.out.println(jo.get(key));
} else {
    keyIterator = jo.keys();
    while (keyIterator.hasNext()) {
    key1 = (String) keyIterator.next();
    if (jo.get(key1) instanceof JSONObject) {
        if (!jo.has(key))
        parseJson(jo.getJSONObject(key1), key);
    } else if (jo.get(key1) instanceof JSONArray) {
        JSONArray jsonarray = jo.getJSONArray(key1);
        Iterator<?> itr = jsonarray.iterator();
        while (itr.hasNext()) {
        String arrayString = itr.next().toString();
        JSONObject jo1 = new JSONObject(arrayString);
        if (!jo1.has(key)) {
            parseJson(jo1, key);
        }
        }

    }
    }
}
}

1
你的回答可以通过添加支持信息来改进。请[编辑]以添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案正确。您可以在帮助中心找到有关如何编写好答案的更多信息。 - Community

0

同样的事情也可以使用GSON完成,但是不是使用GSON转换器适配器将其转换为POJO。我们将手动解析它,这在处理动态JSON数据时给了我们更大的灵活性。
假设JSON格式在我的情况下如下所示。

{
  "dateWiseContent": {
    "02-04-2017": [
      {
        "locality": " Cross Madian Cross Rd No 4"
      }
    ],
    "04-04-2017": [
      {
        "locality": "Dsilva Wadi"
      },
      {
        "locality": " Cross Madian Cross Rd No 4",
        "appointments": []
      }
    ]
  }
}

在这种情况下,dateWiseContent 具有 动态对象键,因此我们将使用 JsonParser 类解析此 JSON 字符串。
  //parsing string response to json object
 JsonObject jsonObject = (JsonObject) new JsonParser().parse(resource);
  //getting root object
 JsonObject dateWiseContent = jsonObject.get("dateWiseContent").getAsJsonObject();

使用以下代码获取动态键:Map.Entry<String, JsonElement>

  // your code goes here
         for (Map.Entry<String, JsonElement> entry : dateWiseContent.entrySet()) {

           //this gets the dynamic keys
            String  dateKey = entry.getKey();

            //you can get any thing now json element,array,object according to json.

            JsonArray jsonArrayDates = entry.getValue().getAsJsonArray();
            int appointmentsSize = jsonArrayDates.size();

             for (int count = 0; count < appointmentsSize; count++) {

                   JsonObject objectData = jsonArrayDates.get(count).getAsJsonObject();
                   String locality = objectData.get("locality").getAsString();


             }
        }

同样地,可以使用Map.Entry<String,JsonElement>来解析任何级别的动态json。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接