Solution 1 :
If you want to parse unknown json, you should use something like this:
Iterator<?> iterator = jsonObject.keys();
while (iterator.hasNext()) {
String key = (String)iterator.next();
//do what you want with the key.
}
Problem :
I’m working on project in which I have to implement on API. This API repsonse is objects of ArrayList. Can you please help me with how to access the sub-arraylist. I’m using retrofit2 & GSON.
As shown in following JSON schema, brand names will be added in brandsonly
by admin, and it will be added in allorders
as a arraylist which have multiple sub-objects.
Like, if admin add Redmi
in the brandsonly
then it will create Redmi[]
in the allorders
.
{
"status": "success",
"brandsonly": [
{
"_id": "",
"brandname": "SAMSUNG"
},
{
"_id": "",
"brandname": "VIVO"
},
{
"_id": "",
"brandname": "NOKIA"
},
{
"_id": "",
"brandname": "IPHONE"
}
],
"allorders": {
"SAMSUNG": [],
"VIVO": [],
"NOKIA": [],
"IPHONE": [
{
"_id": "",
"order_id": "",
"__v": 0,
"adminconfirmation": 1,
"finalpricetodeduct": 30950
},
{
"_id": "",
"order_id": "",
"__v": 0,
"adminconfirmation": 1,
"finalpricetodeduct": 30950
}
]
}
}
My Retrofit call from activity:
final AllOrdersResponse allOrdersResponse = new AllOrdersResponse(userID);
Call<AllOrdersResponse> responseCall = retrofit_interface.allOrderResponse(allOrdersResponse, "Bearer " + AuthToken);
responseCall.enqueue(new Callback<AllOrdersResponse>() {
@Override
public void onResponse(@NotNull Call<AllOrdersResponse> call, @NotNull Response<AllOrdersResponse> response) {
AllOrdersResponse response1 = response.body();
}
@Override
public void onFailure(@NotNull Call<AllOrdersResponse> call, @NotNull Throwable t) {
if (t instanceof SocketTimeoutException)
Toast.makeText(context, "Socket Time out. Please try again.", Toast.LENGTH_LONG).show();
else
Toast.makeText(context, t.toString(), Toast.LENGTH_LONG).show();
}
});
AllOrdersResponse POJO Class.
public class AllOrdersResponse {
@SerializedName("status")
public String status;
@SerializedName("allorders")
public Allorders allorders;
public List<Brandsonly> brandsonly;
public String getStatus() {
return status;
}
public Allorders getAllorders() {
return allorders;
}
public List<Brandsonly> getBrandsonly() {
return brandsonly;
}
}
Also created the BrandResponse
POJO class for each brand response.
public class BrandResponse{
@SerializedName("_id")
public String ID;
public String order_id;
public String __v;
public String adminconfirmation;
public String finalpricetodeduct;
//And getters also there
}
Comments
Comment posted by ADM
What does the class
Comment posted by mr.volatile
I’ve updated question with
Comment posted by This
In this case
Comment posted by mr.volatile
Yes, Thank you. Thats what I was looking for.
Comment posted by mr.volatile
And What if admin added brand
Comment posted by Roman Shtykalo
You still can parse it with 2nd part of code, just iterating through keys of ‘allorders’ jsonObject.