简体   繁体   中英

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?

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

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());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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