繁体   English   中英

使用 GSON 解析 JSON 文件

[英]Parse JSON file 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"]
        }
    }
}

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

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

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...
}

然后只需使用:

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

其中yourJson可以是String 、任何ReaderJsonReaderJsonElement

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

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

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

我正在使用 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();
}
}

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

Gson JsonReader 文档解释了如何处理JsonObjectsJsonArrays解析:

  • 在数组处理方法中,首先调用 beginArray() 来使用数组的左括号。 然后创建一个累积值的 while 循环,当 hasNext() 为 false 时终止。 最后,通过调用 endArray() 读取数组的右括号。
  • 在对象处理方法中,首先调用 beginObject() 来使用对象的左大括号。 然后创建一个 while 循环,根据名称为局部变量赋值。 当 hasNext() 为 false 时,此循环应终止。 最后,通过调用 endObject() 读取对象的右大括号。

暂无
暂无

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

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