Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse json with unknown key by Retrofit?

I want to parse this JSON by Retrofit (i don't know field names{xxx,yyy,zzz}) I tried some Maps, but I did something wrong. Please help me parse this damn json

    {
        xxx: [
        {
        name: "name1",
        description: "desc1"
        }
        ],
        yyy: [
        {
        name: "name2",
        description: "desc2"
        }
        ],
        zzz: [
        {
        name: "name3",
        description: "desc3"
        },
{
        name: "name4",
        description: "desc4"
        }
        ]
        }

---Solution---

I tried create class responce, but it wrong way

public class DishesCategoryResponse {
    public Map<String, List<Dish>> settingsMap;
}

Then i tried this and it works

@GET("/api/restaurant_menu/{id}")
    Observable<Map<String, List<Dish>>> getDishesCategory(@Path("id") long id);
like image 305
MrKosherno Avatar asked Oct 27 '25 03:10

MrKosherno


1 Answers

One day I had a similar task. Ain't sure my solution is perfect, but it may help you.

I had this json file:

Json screenshot

final JSONObject bodyObject = new JSONObject(body);
final JSONObject activities = bodyObject.getJSONObject("activities");
final Iterator<String> keys = activities.keys(); // you can iterate through all keys

final List<ContactActivity> contactActivityInfoList = new ArrayList<ContactActivity>();

while (keys.hasNext()) {
    final String key = keys.next();

    final String jsonString = activities.getJSONObject(key).toString();
    final ContactActivity contactActivity =
                mGson.fromJson(jsonString, ContactActivity.class);

    contactActivityInfoList.add(contactActivity);
}
like image 130
Anton Shkurenko Avatar answered Oct 30 '25 05:10

Anton Shkurenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!