[英]Retrofit parse dynamic JSON response key (Android)
I've a JSON structure given below. 我在下面给出了JSON结构。 As you can see, the branch key can either be an array or an object.
如您所见, 分支键可以是数组或对象。 How am i supposed to handle this?
我应该如何处理呢? Basically if there are more than 1 instances of branch , it becomes an array, else it continues to show one single object.
基本上,如果branch的实例超过1个,它将成为一个数组,否则它将继续显示一个对象。 How should i handle this.
我该如何处理。 It gives me a conversion error at runtime since my POJO class contains
Branch branch
and this is an object decleration. 因为我的POJO类包含
Branch branch
,所以这给我带来了转换错误,这是一个对象分离。 If i want to handle the array decleration, it will be Branch[] branch
. 如果我要处理数组清理,它将是
Branch[] branch
。 How can i make Branch
class behave dynamically based on every tree_type
by position. 如何使
Branch
类根据每个tree_type
的位置动态地表现。
tree: [
{
tree_type:
{
branch:
{
field1 :val1
field2 : val2
}
}
tree_type:
{
branch:
{
field1 :val1
field2 : val2
}
}
tree_type:
{
branch:
[
{
field1 :val1
field2 : val2
}
{
field1 :val1
field2 : val2
}
{
field1 :val1
field2 : val2
}
]
}
}
],
You have to retrieve and check the type of the the "branch" object. 您必须检索并检查“分支”对象的类型。
Try this: 尝试这个:
List<Branch> branches = new ArrayList<>();
if (jsonObject.has("branch") && jsonObject.get("branch") instanceof JSONObject) {
// it is a JSONObject
JSONObject branch = jsonObject.getJSONObject("branch");
// parse your branch : Branch branchObject = ...
branches.add(branchObject);
} else if (jsonObject.has("branch") && jsonObject.get("branch") instanceof JSONArray) {
// it is an JSONArray
JSONArray branchArray = jsonObject.getJSONArray("branch");
// loop branches
for (int i = 0; i < branchArray.length(); i++)
{
if (branchArray.get(i) instanceof JSONObject) {
JSONObject branch = branchArray.getJSONObject(i);
// parse your branch : Branch branchObject = ...
branches.add(branchObject);
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.