代码之家  ›  专栏  ›  技术社区  ›  Gunaseelan

基于GSON的递归JSON数据解析

  •  -2
  • Gunaseelan  · 技术社区  · 7 年前

    [
      {
        "Name": "Fruits",
        "Quantity": "10",
        "isCheckBox": false,
        "List": [
          {
            "Name": "Mango",
            "Quantiy": "10",
            "iScheckBox": true,
            "List": null
          },
          {
            "Name": "Apple",
            "Quantiy": "10",
            "iScheckBox": false,
            "List": [
              {
                "Name": "Simla",
                "Quantiy": "10",
                "iScheckBox": true,
                "List": null
              },
              {
                "Name": "Fuji",
                "Quantiy": "10",
                "iScheckBox": false,
                "List": []
              }
            ]
          }
        ]
      },
      {
        "Name": "Fruits",
        "Quantity": "10",
        "isCheckBox": false,
        "List": [
          {
            "Name": "Mango",
            "Quantiy": "10",
            "iScheckBox": true,
            "List": null
          },
          {
            "Name": "Apple",
            "Quantiy": "10",
            "iScheckBox": false,
            "List": [
              {
                "Name": "Simla",
                "Quantiy": "10",
                "iScheckBox": true,
                "List": null
              },
              {
                "Name": "Fuji",
                "Quantiy": "10",
                "iScheckBox": false,
                "List": []
              }
            ]
          }
        ]
      }
    ]
    

    注意:如果isCheckBox值为false,则将检查列表值以获取内部对象。

    不知道到底有多深的层次,它可能会结束,或者继续下去。如何为这样的JSON数据定义POJO类?

    2 回复  |  直到 7 年前
        1
  •  0
  •   Clint Paul    7 年前
    public class Shopping
    {
    private Fruits Fruits;
    
    private String Vegetables;
    
    public Fruits getFruits ()
    {
        return Fruits;
    }
    
    public void setFruits (Fruits Fruits)
    {
        this.Fruits = Fruits;
    }
    
    public String getVegetables ()
    {
        return Vegetables;
    }
    
    public void setVegetables (String Vegetables)
    {
        this.Vegetables = Vegetables;
    }
    
    @Override
    public String toString()
    {
        return "ClassPojo [Fruits = "+Fruits+", Vegetables = "+Vegetables+"]";
    }}
    

    这对于上述给定的样本就足够了。请试一试

        2
  •  0
  •   Gunaseelan    7 年前

    其实解决方法很简单,

    public class FruitsEntity {
        String Name;
        String Quantity;
        boolean isCheckBox;
        ArrayList<FruitsEntity> List;
    }
    

    你可以用,

    Gson gson = new Gson();
    ArrayList<FruitsEntity> nestEntities = gson.fromJson(jsonData, new TypeToken<ArrayList<FruitsEntity>>() {
    }.getType());