Recursive JSON data parsing using GSON

Sometime we may have JSON data like,

[
  {
    "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": []
          }
        ]
      }
    ]
  }
]

Note : If the isCheckBox value is false then will check the list values to get the inner objects.

Don't know the end of depth level, it may end, or goes on. How to define the POJO class for JSON data like this?

2 answers

  • answered 2018-09-17 05:59 Clint Paul

    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+"]";
    }}
    

    This will be enough for the above given sample. Please try

  • answered 2018-09-17 09:50 Gunaseelan

    Actually the solution is very simple,

    Here is entity,

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

    And you can parse using,

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