I'm trying to Parse a nested JSON Array using Gson and showing the array inside recyclerview. The way i'm parsing the JSON array doesn't seems okay/proper to me but its doing the job. But i want to know how to handle such cases properly.
Sample JSONArray
{
"Status":"success",
"Response":[
{
"Title":"First Title",
"Code":"20210209",
"Content":[
{
"field_1":"field_1_text",
"field_2":true
},
{
"field_1":"field_1_text",
"field_2":true
}
]
},
{
"Title":"Second Title",
"Code":"2021020902",
"Content":[
{
"field_1":"field_1_text_2",
"field_2":true
},
{
"field_1":"field_1_text_2",
"field_2":false
}
]
}
]
}
Parsing with Gson (focused only on Response array) :
List<ResponseArrayObject> responseList = new ArrayList<>();
Type listType = new TypeToken<ArrayList<ResponseArrayObject>>(){}.getType();
responseList.addAll(new Gson().fromJson(response.toString(), listType));
Till here, I'm parsing the complete ResponseArray
in one single main list. After this I've created a new List of different objecttype
with Getter/Setter and iterate through responseList
and if the Content.size()
is greater than 0, I'm doing the following.
for(ResponseArrayObject responseO:responseList){
if(responseO.Content.size()>0){
CustomResponseList.add(new CustomerResponse(responseO.Title,null));
for(Response.Content c:responseO.Content){
CustomResponseList.add(new CustomerResponse(null,c));
}
}
}
This way i'm getting one list with different type of data i.e.
[
{
"Title" : "First Title",
"Content" : null;
},{
"Title" : null,
"Content" : {
"field_1": "field_1_text",
"field_2": true
},
{
"Title" : "null",
"Content" : {
"field_1": "field_1_text",
"field_2": true
},{
"Title" : "Second Title",
"Content" : null;
},{
"Title" : "null",
"Content" : {
"field_1": "field_1_text_2",
"field_2": true
},
{
"Title" : "null",
"Content" : {
"field_1": "field_1_text_2",
"field_2": true
}
}
]
Now this one is simple Array with nested OBJECT
and I can simple iterated through this array in recycerlview adapter
without any issues and use different layout configs based on null value
.
But i feel like it is not the right way. Please someone look into it and tell me how to do it properly.
A lot of links here on SO are basically parsing the Nested Arrays which i can do easily but no ones talking about how to use the parsed Nested arrays in Recyclerview Adapter.