且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用 GSON 解析嵌套的 JSON 数据

更新时间:2023-01-12 11:02:59

您只需要创建一个 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);