[英]Recursive JSON data parsing using GSON
有时我们可能有 JSON 数据,例如,
[
{
"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 类?
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+"]";
}}
这对于上面给出的样本就足够了。 请尝试
其实解决方法很简单
这里是实体,
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());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.