【问题标题】:Swift 3 Alamofire Swifty json parsing issueSwift 3 Alamofire Swifty json 解析问题
【发布时间】:2017-01-22 17:54:00
【问题描述】:

我在解析 json 时遇到问题。我一直在寻找如何解决这个问题,但没有成功。

我的 json 输出如下所示:

{
    "data": [{
        "type": "schedules",
        "id": "1",
        "attributes": {
            "date": "2016-12-24"
        },
        "relationships": {
            "user": {
                "data": {
                    "type": "users",
                    "id": "8"
                }
            },
            "statuses": {
                "data": [{
                    "type": "statuses",
                    "id": "2"
                }]
            },
            "events": {
                "data": [{
                    "type": "events",
                    "id": "7"
                }]
            }
        }
    }, {
        "type": "schedules",
        "id": "2",
        "attributes": {
            "date": "2016-12-04"
        },
        "relationships": {
            "user": {
                "data": {
                    "type": "users",
                    "id": "8"
                }
            },
            "statuses": {
                "data": [{
                    "type": "statuses",
                    "id": "12"
                }, {
                    "type": "statuses",
                    "id": "16"
                }, {
                    "type": "statuses",
                    "id": "17"
                }]
            },
            "events": {
                "data": [{
                    "type": "events",
                    "id": "16"
                }, {
                    "type": "events",
                    "id": "17"
                }, {
                    "type": "events",
                    "id": "1"
                }]
            }
        }
    }, {
        "type": "schedules",
        "id": "3",
        "attributes": {
            "date": "2002-12-03"
        },
        "relationships": {
            "user": {
                "data": {
                    "type": "users",
                    "id": "7"
                }
            },
            "statuses": {
                "data": [{
                    "type": "statuses",
                    "id": "3"
                }, {
                    "type": "statuses",
                    "id": "11"
                }]
            },
            "events": {
                "data": [{
                    "type": "events",
                    "id": "4"
                }, {
                    "type": "events",
                    "id": "19"
                }]
            }
        }
    }],
    "included": [

        {
            "type": "events",
            "id": "6",
            "attributes": {
                "name": "streamline leading-edge portals",
                "event_type": "3",
                "start_time": "22:20:04",
                "end_time": "20:19:22"
            }
        }, {
            "type": "events",
            "id": "11",
            "attributes": {
                "name": "maximize dynamic niches",
                "event_type": "8",
                "start_time": "15:51:06",
                "end_time": "22:24:56"
            }
        }, {
            "type": "events",
            "id": "12",
            "attributes": {
                "name": "transition vertical methodologies",
                "event_type": "1",
                "start_time": "19:55:59",
                "end_time": "00:27:42"
            }
        }
    ]
}

我快速获得这个看起来像这样:

func getSchedules<T: JSONObject>(_ success: @escaping ([T]) -> Void) {
        self.getAllScheduleData { (json) in

            var items: [T] = []

            if let jsonArray = json.array {
                for jsonItem in jsonArray {
                    items.append(T.fromJSONComplete(json: jsonItem) as! T)
                }
            }

            success(items)
        }
    }

self.getAllScheduleData 使用 Alamofire 进行 API 调用

这里的问题是,json.array 总是空的。据我了解,它应该始终类似于:json["items"].array.

但是,这个 json 没有可调用的顶层。即物品。

我现在的选择是获取 json["data"] 或 json["included"]。但我想让他们都把它解析成一个对象。

不幸的是,不确定如何更好地解释这一点 如果您需要更多信息,请尽管询问。

我正在使用:Swift 3、Alamofire、SwiftyJSON

编辑: 我还考虑在从调用中获取 json 后为其添加顶层。 即项目{数据{},包含{}} 但没做好

如果我按照 Emptyless 的建议使用 for in 语法,我可能必须更改此方法的签名,对吧?

static func fromJSONComplete<T : Object>(json: JSON) -> T {

        let s = Schedule()

        if let id = json["data"]["id"].string {
            s.id = id
        }

        if let date = json["data"]["attributes"]["date"].string {
            s.date = date
        }

        if let type = json["data"]["type"].string {
            s.type = type
        }

        if let includedArray = json["included"].array {
            for userJson in includedArray {
                if userJson["type"].string == "users" {
                    let user : User = User.fromJSON(json: userJson)

                    s.users.append(user)
                }
            }

            for statusJson in includedArray {
                if statusJson["type"].string == "statuses" {
                    let status : Status = Status.fromJSON(json: statusJson)
                    s.statuses.append(status)
                }
            }

            for eventJson in includedArray {
                if eventJson["type"].string == "events" {
                    let event : Event = Event.fromJSON(json: eventJson)
                    s.events.append(event)
                }
            }
        }

        return s as! T
    }

提前谢谢你!

克里斯

【问题讨论】:

  • 你试过for in 语法吗? for (key, subJSON) in json { }。然后,您可以使用 json[key] 遍历“data”和“included”这两个键。
  • @Emptyless 我试过了,但我想我并不完全理解它是如何使用的。能给我一个代码示例吗?

标签: json parsing swift3 alamofire


【解决方案1】:

请求的代码示例:

for (key,subjson) in json {
    for i in 1 ..< json[key].count where subjson.array != nil {
        print("found json for key: \(key): \(json[key][i])")
    }
}

它检查提供的 json 对象并遍历可用的顶级键。如果键包含某个对象的数组,它也会对其进行迭代。

例如,我主要使用的一种方法是打开键并将 json 对象作为初始化程序传递,但它也可以用于拆分函数。

例如

switch(key) {
case "included":
     // Do something
case "data":
    // Do Something
default:
    break
}

【讨论】:

  • 感谢@Emptyless!它奏效了:D 我为你投票,但由于我的声望低,它还没有注册大声笑
猜你喜欢
  • 1970-01-01
  • 2020-11-19
  • 1970-01-01
  • 1970-01-01
  • 2018-07-27
  • 1970-01-01
  • 1970-01-01
  • 2017-01-20
  • 1970-01-01
相关资源
最近更新 更多