如何在Java中访问JSON文件的所有子类和字符串?

问题描述 投票:0回答:1

我需要打印来自不同JSON文件的信息(将在args [0]中指定)并打印出来。

所有可能的访问文件都是这样出现的(这有点是JSON文件的缩短版本)

 {
   "DefinitionSource" : "",
   "Heading" : "Valley Forge National Historical Park",
   "RelatedTopics" : [
        "FirstURL" : //url here
        "Text" : "hello world"
 },
 {
        "FirstURL" : //url here
        "Text" : "hello world"
 },
 ]

根据选择访问的JSON文件,有许多这些子类是不同的。对于指定的JSON文件,我需要访问标记为“Text”的JSON文件中的所有字符串。这是我正在使用的一些代码:

JsonReader reader = Json.createReader(new StringReader(jsonString));
JsonObject mainObject = reader.readObject(); 
JSONObject RelatedTopic = json.getJSONObject("RelatedTopics");
String text = RelatedTopic.getString("Text");
System.out.println("Textual Description: " + text);
java json parsing reader
1个回答
1
投票
void find_text(JsonObject obj){
    Iterator<String> keys = jsonObject.keys();
    while (keys.hasNext()){
        String key = keys.next()
        if (key == "Text") {
            .. do your stuff ....
        } else if (obj.get(key) instanceof JSONObject) 
            find_text(obj.get(key))

      }
}

这将搜索JSON文本的所有键,如果它是一个对象,则递归调用该方法。

© www.soinside.com 2019 - 2024. All rights reserved.