使用 GSON 解析 JSON 文件 [英] Parse JSON file using GSON

查看:47
本文介绍了使用 GSON 解析 JSON 文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to parse this JSON file in JAVA using GSON :

{
    "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> 元素.

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.

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

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.

推荐答案

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

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:

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 可以是 字符串,任何ReaderJsonReaderJsonElement.

Where yourJson can be a String, any Reader, a JsonReader or a JsonElement.

最后,如果您想访问任何特定字段,您只需:

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

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

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

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.

这篇关于使用 GSON 解析 JSON 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆