使用 GSON 解析嵌套的 JSON 数据 [英] Parsing nested JSON data using GSON

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

问题描述

我正在尝试使用具有以下结构的 Java 中的 gson 解析一些 JSON 数据,但通过查看在线示例,我找不到任何可以完成这项工作的内容.

I'm trying to parse some JSON data using gson in Java that has the following structure but by looking at examples online, I cannot find anything that does the job.

有人可以提供帮助吗?

{
    "data":{
        "id":[
            {
                "stuff":{

                },
                "values":[
                    [
                        123,
                        456
                    ],
                    [
                        123,
                        456
                    ],
                    [
                        123,
                        456
                    ],

                ],
                "otherStuff":"blah"
            }
        ]
    }
}

推荐答案

您只需要创建一个 Java 类结构来表示 JSON 中的数据.为此,我建议您将 JSON 复制到这个 online JSON Viewer 中,您将看到你的 JSON 结构更清晰...

You just need to create a Java class structure that represents the data in your JSON. In order to do that, I suggest you to copy your JSON into this online JSON Viewer and you'll see the structure of your JSON much clearer...

基本上你需要这些类(伪代码):

Basically you need these classes (pseudo-code):

class Response
  Data data

class Data
  List<ID> id

class ID
  Stuff stuff
  List<List<Integer>> values
  String otherStuff

请注意,类中的属性名称必须与 JSON 字段的名称匹配!您可以根据您的实际 JSON 结构添加更多属性和类...另外请注意,您的所有属性都需要 getter 和 setter!

Note that attribute names in your classes must match the names of your JSON fields! You may add more attributes and classes according to your actual JSON structure... Also note that you need getters and setters for all your attributes!

最后,您只需要将 JSON 解析为您的 Java 类结构:

Finally, you just need to parse the JSON into your Java class structure with:

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

就是这样!现在您可以使用 getter 和 setter 访问 response 对象中的所有数据...

And that's it! Now you can access all your data within the response object using the getters and setters...

例如,要访问第一个值 456,您需要执行以下操作:

For example, in order to access the first value 456, you'll need to do:

int value = response.getData().getId().get(0).getValues().get(0).get(1);

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

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