使用GSON解析嵌套的JSON数据 [英] Parsing nested JSON data using GSON
问题描述
我试图用Java中的gson解析一些JSON数据,它具有以下结构,但通过在线查看示例,我找不到任何工作。
< p $>
data:{
id :[
{
stuff:{
},
values):[
[
123,
456
],
[
123,
456
],
[
123,
456
] ,
],
otherStuff:blah
}
]
}
}
您只需要创建一个Java类structur e表示您的JSON中的数据。为此,我建议您将JSON复制到此在线JSON查看器中,您将看到你的JSON结构更加清晰... ...
基本上你需要这些类(伪代码):
class Response
数据数据
类数据
列表< ID> id
class ID
Stuff stuff
List< List< Integer>>值
字符串otherStuff
请注意,类中的属性名称必须与您的JSON名称匹配领域!您可以根据您的实际JSON结构添加更多属性和类别......还要注意,您需要获取所有属性的getter和setters!
最后,您只需要
Gson gson = new Gson();解析JSON到你的Java类结构中。
响应响应= gson.fromJson(yourJsonString,Response.class);
就是这样!现在,您可以使用getters和setter访问响应
对象中的所有数据... 例如,为了访问第一个值 456
,您需要这样做:
int value = response.getData()。getId()。get(0).getValues()。get(0).get(1);
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.
Would anyone be able to assist?
{
"data":{
"id":[
{
"stuff":{
},
"values":[
[
123,
456
],
[
123,
456
],
[
123,
456
],
],
"otherStuff":"blah"
}
]
}
}
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
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!
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);
And that's it! Now you can access all your data within the response
object using the getters and setters...
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屋!