使用GSON解析嵌套的JSON数据

编程入门 行业动态 更新时间:2024-10-06 18:33:29
本文介绍了使用GSON解析嵌套的JSON数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我试图用Java中的gson解析一些JSON数据,它具有以下结构,但通过在线查看示例,我找不到任何工作。

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数据

本文发布于:2023-11-26 23:30:53,感谢您对本站的认可!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:嵌套   数据   GSON   JSON

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!