改造以解析具有无限数量的对象名称的 json [英] Retrofit to parse json with an indefinite number of object names

查看:54
本文介绍了改造以解析具有无限数量的对象名称的 json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用改造来处理 rest-api 调用.我有一个返回以下 json 的 rest API

I'm using retrofit to handle rest-api calls. I have a rest API that returns the following json

    "MyObject": {
      "43508": {
        "field1": 4339,
        "field2": "val",
        "field3": 15,
        "field4": 586.78
      },
      "1010030": {
        "field1": 1339,
        "field2": "val212",
        "field3": 1,
        "field4": 86.78
      },...
    }

请注意对象 MyObject 包含名称实际上是 id 的对象.对于所有其他其他 API,我正在使用改造没有问题.在这种情况下,似乎无法使用标准方法:定义一个包含响应中预期字段的类.

Please notice that the object MyObject contains objects with a name that is actually an id. For all the other rest APIs I'm using retrofit without problems. In this case it seems not possible to use the standard approach: defining a class containing the fields expected in the response.

有没有办法把这个json转换成一个包含数组的json

Is there a way to transform this json into a json containing an array of

{
    "field1": xxx,
    "field2": "yyy",
    "field3": www,
    "field4": zzz
}

或者有没有更好的方法来处理这个问题,而无需回到手动"解析 json 中?

Or is there a better way to deal with this problem without going back to "manually" parsing the json?

推荐答案

尝试使用下一个方法:

public class Response {

    Map<String, YourObject> MyObject;
    // getter, setter
}

public interface GitHubService {
  @GET("some_path")
  Call<Response> listMyObjects();
}

你所有的对象都将被解析为 Map.您可以通过 keySet() 方法获取所有 id 的列表或使用 entrySet() 列出所有条目.

All you objects will be parsed to Map. You can get the list of all ids via keySet() method or list all entries with entrySet().

这篇关于改造以解析具有无限数量的对象名称的 json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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