java - 如何在 Android 中使用 Gson 和 Retrofit 解析深层嵌套 json 对象中的字段?

标签 java android retrofit retrofit2 android-json

我有一个独特的情况,我必须从 json 的深层嵌套对象中获取某些时间。这有点复杂,我找不到解决方案,因此寻找想法和方法来解决这个问题

我有一个 json 如下:

[{
        "mySpaceId": 73220,
        "myBuildingId": 14019,
        "myFloorId": 10569,
        "myFloorNumber": "4",
        "myFloorName": "4th Floor",
        "spaceName": "My Room 4",
        "capacity": 5,
        "type": "huddle",
        "busyAt": []
    },
    {
        "mySpaceId": 73219,
        "myBuildingId": 14019,
        "myFloorId": 10569,
        "myFloorNumber": "4",
        "myFloorName": "4th Floor",
        "spaceName": "My room 5",
        "description": null,
        "capacity": 4,
        "type": "huddle",
        "timeZone": "America/New_York",

        "busyAt": [{
            "from": "2019-06-07T23:00:00+0000",
            "to": "2019-06-07T23:15:00+0000",
            "events": [{
                "id": "109142028",
                "series_id": null,
                "recurrence_id": null,
                "uid": "ABCDE",
                "space_id": 73219,
                "start": {
                    "date_time": "2019-06-07T19:00:00-0400",
                    "time_zone": "America/New_York"
                },
                "end": {
                    "date_time": "2019-06-07T19:15:00-0400",
                    "time_zone": "America/New_York"
                },
                "started_at": "2019-06-07T19:00:00-0400",
                "ended_at": "2019-06-07T19:15:00-0400"
            }]
        }]
    }
]

我用这个:http://www.jsonschema2pojo.org/从上面的 json 字符串生成一个类。 我想知道如何检索 "started_at": "2019-06-07T19:00:00-0400",

从 busyAt-> 事件到上面站点生成的我的主模型类? 与mySpaceId处于同一级别。我目前使用以下内容:

 public List<BusyAt> getBusyAt() {
        return busyAt;
    }

    public void setBusyAt(List<BusyAt> busyAt) {
        this.busyAt = busyAt;
    }

有没有办法可以检索此级别的started_at并以以下格式解析日期和时间:上午8:00?在我的代码中使用它。

知道如何解决这个问题吗? 谢谢!如果这令人困惑或需要更多说明,请告诉我,很乐意发布更多代码。

最佳答案

你必须做这样的事情:

JSONArray array = new JSONArray(result);
for (int i = 0; i < array.length(); ++i) {
JSONObject jObj = array.getJSONObject(i);

String busyAt = jObj.getString("busyAt");
// convert it to json array 
JSONArray busyAtArray = new JSONArray(busyAt)
String endedAt = busyAtArray.getJSONObject(0).getString("ended_at")
// convert the string and get the time from it

}

我希望你能从中得到一个总体的想法。这段代码当然可以用更好的方式编写。

关于java - 如何在 Android 中使用 Gson 和 Retrofit 解析深层嵌套 json 对象中的字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56501897/

相关文章:

java - Android:画廊选择器和相机 Intent 在 onActivityresult 上崩溃

java - 通过 Fresco 库加载的适配器图像不规则

java - 在 Android 应用程序中显示图片

java - Spring 启动 Restful API : Simple authentication

java - Android - Jar 集成 - Dalvik 错误 1 ​​或无法解析父类(super class)

使用 GPS 的 Android App 功耗

android - 在蓝牙 LE 连接中使用 ScanFilter 时没有回调

java - 如何为此 REST 响应编写 getter setter 类以进行改造

android - 改造 - 子域和目录

java - 从 retrofit2 获取字符串响应体