简体   繁体   English

使用 GSON 解析 JSON 文件

[英]Parse JSON file using GSON

I want to parse this JSON file in JAVA using 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 app3 element and finally the name element.但我不知道如何加入根元素,即 : 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 元素的情况。

Imo, the best way to parse your JSON response with GSON would be creating classes that "match" your response and then useGson.fromJson() method. Imo,使用 GSON 解析 JSON 响应的最佳方法是创建“匹配”响应的类,然后使用Gson.fromJson()方法。
For example:例如:

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 yourJson can be aString , any Reader , a JsonReader or a JsonElement .其中yourJson可以是String 、任何ReaderJsonReaderJsonElement

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 的整体理念。

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();
}
}

One thing that to be remembered while solving such problems is that in JSON file, a { indicates a JSONObject and a [ indicates JSONArray .解决此类问题时要记住的一件事是,在 JSON 文件中, {表示JSONObject[表示JSONArray If one could manage them properly, it would be very easy to accomplish the task of parsing the JSON file.如果管理得当,解析JSON文件的任务就很容易完成了。 The above code was really very helpful for me and I hope this content adds some meaning to the above code.上面的代码对我真的很有帮助,我希望这个内容给上面的代码增加了一些意义。

The Gson JsonReader documentation explains how to handle parsing of JsonObjects and JsonArrays : Gson JsonReader 文档解释了如何处理JsonObjectsJsonArrays解析:

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

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

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