改造,如何用可变键分析JSON对象 [英] Retrofit, how to parse JSON objects with variable keys

查看:97
本文介绍了改造,如何用可变键分析JSON对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,我知道我的标题很糟糕,因为我没有提出更好的建议。我开启了建议。



我正在使用翻新来获取数据从这种类型的api: @GET(users / {userid})



我对此感到满意,问题是当我使用id列表调用与 @POST(users / widget)相同的api时。我有以下答案:

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

long_hash_id是典型的525558cf8ecd651095af7954
它对应于附加到它的用户的ID。



当我没有使用改造时,我使用Gson以流模式逐一获取每个用户。但我不知道如何告知改造。



希望我清楚,
先谢谢您。



-----------解决方案:



我这样做了我的界面:

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

我只是给了我的ArrayList的id。非常感谢

解决方案

Gson 能够处理JSON对象像你发布的变量键。在这种情况下,你需要做的是声明一个 Map< String,ModelClass> ,其中 ModelClass 是要表示的JSONObject的内容


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

解决方案

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

这篇关于改造,如何用可变键分析JSON对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆