繁体   English   中英

使用 Gson Android 动态 Json 解析

[英]Dynamic Json Parsing Using Gson Android

我有一个如下所述的json。

{
  "product": [
    {
      "classification": "abc",
      "ABC": [
        {
          "classification": "abc",
          "name": "abc new product one",
          "price": "10775.0000",
        },
        {
          "classification": "abc",
          "name": "abc new product two",
          "price": "12725.0000",
        }
      ]
    },
    {
      "classification": "def",
      "DEF": [
        {
          "classification": "def",
          "name": "def product one",
          "price": "728.0000",
        },
        {
          "classification": "def",
          "name": "def product two",
          "price": "1263.0000",
        },
      ]
    }
  ],
  "status": "OK",
  "message": "success"
}

在上面的json中,大写的key是动态的

(例如:ABC、DEF)

. 我创建了 pojo 类,如下所示:

    public class ProductResponse{

       private String status;
       private String message;
       private List<Products>;

       Getters And Setters
    }

    public class Products{

       private String classification;

    }

我正在努力编写 Products pojo 类的下一部分,作为大写字母的键

(例如:ABC、DEF)

是动态的。 我正在使用 volley 库来获取数据和解析我正在使用 gson 库。 请帮帮我。

你的问题是动态键,我发现它不是动态的。 如我所见,对于product数组中的每个元素, classification键的值是下一个键。 唯一的区别是它们是大写字母。

{
  "classification": "def",
  "DEF": [
    {
      "classification": "def",
      "name": "def product one",
      "price": "728.0000",
    },
    {
      "classification": "def",
      "name": "def product two",
      "price": "1263.0000",
    },
  ]
}

就像这里的"classification": "def"和下一个键是DEF 我在这里要做的是获取classification键的值, classification字符串中的所有字母大写,然后将其用作key

不能有动态名称。 原因是 json 中的名称需要链接到对象中的属性。 我建议您在 json 和模型中添加“分类”属性,如下所示:

{
  "type": "def",
  " results": [
    {
      "name": "def product one",
      "price": "728.0000",
    },
    {
      "name": "def product two",
      "price": "1263.0000",
    },
  ]
}



public final class ProductResponse{

       private String status;
       private String message;
       private List<Products> product = new Arraylist<>();

       // Getters And Setters
    }

    public final class Products{

       private String type; // type of product // ABC or DEF
       private List<Result> results = new Arraylist<>(); 

      // Getters And Setters
    }


     public final class Result{

       private String name;
       private String price;


     // Getters And Setters
    }

您的产品类别现在有一个与分类相关的结果列表!

希望能帮助到你 !

暂无
暂无

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

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