对于我来说,我有以下json响应:
{
"all": {
"loc1": [
{
"userId": "1",
"userName": "user1"
},
{
"userId": "2",
"userName": "user2"
},
{
"userId": "2",
"userName": "user2"
},
{
"userId": "1",
"userName": "user1"
},
{
"userId": "2",
"userName": "user2"
}
],
"loc2": [
{
"userId": "1",
"userName": "user1"
},
{
"userId": "2",
"userName": "user2"
},
{
"userId": "2",
"userName": "user2"
},
{
"userId": "1",
"userName": "user1"
},
{
"userId": "2",
"userName": "user2"
}
]
}
}
但是现在,动态创建了数组loc1和loc2的名称。我如何获得“所有” json数组的响应以及动态创建的数组的名称。我尝试过这样的事情:
class EventResponse() {
@SerializedName("all")
val events: List<List<Event>> = mutableListOf()
}
但是我得到一个错误:
预期为BEGIN_ARRAY,但为BEGIN_OBJECT。
如何获取动态创建的数组及其名称?
答案 0 :(得分:0)
在这种情况下,您可以使用JSONObject获取动态值,只需将改装响应转换为JSONObject,因为您必须更改改装调用的响应类型
Call<ResponseBody> call = exampleApi();
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Response<ResponseBody> response, Retrofit retrofit) {
String result = response.body().string();
JSONObject object = new JSONObject(result);
// can get any value from keys
// for example in your case
JSONArray array1 = object.getJSONObject('all').getJSONArray('loc1');
//similarly just change key to loc2 and so on
JSONArray array2 = object.getJSONObject('all').getJSONArray('loc2');
}
@Override
public void onFailure(Throwable t) {
}
});