Retrofit, how to parse JSON objects with variable keys

心不动则不痛 提交于 2020-01-11 09:51:30

问题


First I know my title is bad as I didn't come up with better, I'm opened to suggestion.

I'm using retrofit to get data from an api of this kind : @GET("users/{userid}")

It works fine and I'm happy with it, the problem is when I call the same api with @POST("users/widget") with a list of ids. I have the following answer :

{
  "long_hash_id": {
    "_id": "long_hash_id"
    .......
  },
  "long_hash_id": {
    "_id": "long_hash_id",
    .....
  },
  ........
}

the "long_hash_id" is typicaly "525558cf8ecd651095af7954" it correspond to the id of the user attached to it.

When I didn't use retrofit, I used Gson in stream mode to get each user one by one. But I don't know how to tell retrofit.

Hope I'm clear and Thank you in advance.

----------- Solution :

I made my interface this way :

@FormUrlEncoded
@POST(AppConstants.ROUTE_USER_GROUP)
Call<Map<String,User>> getUsers( @Field("ids") List<String> param, @QueryMap Map<String,String> options);

and I simply gave my ArrayList of ids. Thank you very much


回答1:


Gson is able to deal with JSON objects with variable keys like the one you posted. What you have to do, in this case, is to declare a Map<String, ModelClass>, where ModelClass is the content of the JSONObject you want to represent



来源:https://stackoverflow.com/questions/33674249/retrofit-how-to-parse-json-objects-with-variable-keys

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!