使用GSON解析JSON文件

时间:2013-05-04 18:45:49

标签: java json parsing gson

我想使用 GSON 解析 JAVA 中的 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"]
        }
    }
}

但我不知道如何加入根元素:描述符,之后是 app3 元素,最后是名称元素。

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

3 个答案:

答案 0 :(得分:48)

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

答案 1 :(得分:20)

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

答案 2 :(得分:2)

解决此类问题时需要记住的一件事是,在JSON文件中,{表示JSONObject[表示JSONArray。如果可以正确地管理它们,那么完成解析JSON文件的任务将非常容易。上面的代码对我非常有帮助,我希望这些内容为上面的代码增加了一些含义。

Gson JsonReader documentation解释了如何处理JsonObjectsJsonArrays的解析:

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