Java 使用 GSON 解析 JSON 文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16377754/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-16 06:34:20  来源:igfitidea点击:

Parse JSON file using GSON

javajsonparsinggson

提问by

I want to parse this JSONfile in JAVAusing GSON:

我想在JAVA 中使用GSON解析这个JSON文件:

{
    "descriptor" : {
        "app1" : {
            "name" : "mehdi",
            "age" : 21,
            "messages": ["msg 1","msg 2","msg 3"]
        },
        "app2" : {
            "name" : "mkyong",
            "age" : 29,
            "messages": ["msg 11","msg 22","msg 33"]
        },
        "app3" : {
            "name" : "amine",
            "age" : 23,
            "messages": ["msg 111","msg 222","msg 333"]
        }
    }
}

but I don't know how to acceed to the root element which is : descriptor, after that the app3element and finally the nameelement.

但我不知道如何加入根元素,即 : descriptor,然后是app3元素,最后是name元素。

I followed this tutorial http://www.mkyong.com/java/gson-streaming-to-read-and-write-json/, but it doesn't show the case of having a root and childs elements.

我遵循了本教程http://www.mkyong.com/java/gson-streaming-to-read-and-write-json/,但它没有显示具有 root 和 childs 元素的情况。

采纳答案by MikO

Imo, the best way to parse your JSON response with GSON would be creating classes that "match" your response and then use Gson.fromJson()method.
For example:

Imo,使用 GSON 解析 JSON 响应的最佳方法是创建“匹配”响应的类,然后使用Gson.fromJson()方法。
例如:

class Response {
    Map<String, App> descriptor;
    // standard getters & setters...
}

class App {
  String name;
  int age;
  String[] messages;
  // standard getters & setters...
}

Then just use:

然后只需使用:

Gson gson = new Gson();
Response response = gson.fromJson(yourJson, Response.class);

Where yourJsoncan be a String, any Reader, a JsonReaderor a JsonElement.

哪里yourJson可以是 a String、 any Reader、 aJsonReader或 a JsonElement

Finally, if you want to access any particular field, you just have to do:

最后,如果您想访问任何特定字段,只需执行以下操作:

String name = response.getDescriptor().get("app3").getName();

You can always parse the JSON manually as suggested in other answers, but personally I think this approach is clearer, more maintainable in long term and it fits better with the whole idea of JSON.

您始终可以按照其他答案中的建议手动解析 JSON,但我个人认为这种方法更清晰,从长远来看更易于维护,并且更符合 JSON 的整体理念。

回答by Gere

I'm using gson 2.2.3

我正在使用 gson 2.2.3

public class Main {

/**
 * @param args
 * @throws IOException 
 */
public static void main(String[] args) throws IOException {

    JsonReader jsonReader = new JsonReader(new FileReader("jsonFile.json"));

    jsonReader.beginObject();

    while (jsonReader.hasNext()) {

    String name = jsonReader.nextName();
        if (name.equals("descriptor")) {
             readApp(jsonReader);

        }
    }

   jsonReader.endObject();
   jsonReader.close();

}

public static void readApp(JsonReader jsonReader) throws IOException{
    jsonReader.beginObject();
     while (jsonReader.hasNext()) {
         String name = jsonReader.nextName();
         System.out.println(name);
         if (name.contains("app")){
             jsonReader.beginObject();
             while (jsonReader.hasNext()) {
                 String n = jsonReader.nextName();
                 if (n.equals("name")){
                     System.out.println(jsonReader.nextString());
                 }
                 if (n.equals("age")){
                     System.out.println(jsonReader.nextInt());
                 }
                 if (n.equals("messages")){
                     jsonReader.beginArray();
                     while  (jsonReader.hasNext()) {
                          System.out.println(jsonReader.nextString());
                     }
                     jsonReader.endArray();
                 }
             }
             jsonReader.endObject();
         }

     }
     jsonReader.endObject();
}
}

回答by VAMSHI PAIDIMARRI

One thing that to be remembered while solving such problems is that in JSON file, a {indicates a JSONObjectand a [indicates JSONArray. If one could manage them properly, it would be very easy to accomplish the task of parsing the JSON file. The above code was really very helpful for me and I hope this content adds some meaning to the above code.

解决此类问题时要记住的一件事是,在 JSON 文件中,a{表示 a JSONObject,a[表示JSONArray. 如果管理得当,解析JSON文件的任务就很容易完成了。上面的代码对我真的很有帮助,我希望这个内容给上面的代码增加了一些意义。

The Gson JsonReader documentationexplains how to handle parsing of JsonObjectsand JsonArrays:

GSON JsonReader文档介绍了如何处理的解析JsonObjectsJsonArrays

  • Within array handling methods, first call beginArray() to consume the array's opening bracket. Then create a while loop that accumulates values, terminating when hasNext() is false. Finally, read the array's closing bracket by calling endArray().
  • Within object handling methods, first call beginObject() to consume the object's opening brace. Then create a while loop that assigns values to local variables based on their name. This loop should terminate when hasNext() is false. Finally, read the object's closing brace by calling endObject().
  • 在数组处理方法中,首先调用 beginArray() 来使用数组的左括号。然后创建一个累积值的 while 循环,当 hasNext() 为 false 时终止。最后,通过调用 endArray() 读取数组的右括号。
  • 在对象处理方法中,首先调用 beginObject() 来使用对象的左大括号。然后创建一个 while 循环,根据名称为局部变量赋值。当 hasNext() 为 false 时,此循环应终止。最后,通过调用 endObject() 读取对象的右大括号。