I've a JSON structure given below. 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. 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. If i want to handle the array decleration, it will be Branch[] branch
. How can i make Branch
class behave dynamically based on every tree_type
by position.
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);
}
}
}
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.