简体   繁体   English

使用 Gson 解析嵌套的 json 值

[英]Parsing nested json values using Gson

I have seen many examples on parsing data, but it is still confusing me.我看过很多解析数据的例子,但仍然让我感到困惑。

I am using gson to parse json data in java.我正在使用 gson 来解析 java 中的 json 数据。

Here is my json data--这是我的 json 数据——

{
"success": true,
"message": "login",
"data": [
    {
        "value1" : "value1",
        "vaue2": {
            "name": "myname"
             },
        "value 3": "value 3",
    }]
}

I want to retrieve "value 1" and "value2".我想检索“值 1”和“值 2”。

I have created pojo classes.我创建了 pojo 类。 But when I am trying to retrieve the values using these statements it is returning empty value.但是,当我尝试使用这些语句检索值时,它返回的是空值。

 Gson gson = new Gson();
 Datum datum = gson.fromJson(json_string,Datum.class);
 String code = datum.getValue1(); 

My model class:我的 model class:

public class Datum {
    private String value1;
    @SerializedName("value1")
    /////more code

public String getValue1() {
    return value1;
}

But when I try to parse values for "success" and "message" as above, it is fine.但是当我尝试像上面那样解析“成功”和“消息”的值时,这很好。 Problem is when Im trying to parse nested values.问题是当我尝试解析嵌套值时。

you will have to create objects for nested structures您将不得不为嵌套结构创建对象

public class Datum
   @SerializedName("value1")
   private String value1;

   @SerializedName("data")
   private Data[] data;


public class Data
   private String value;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM