【问题标题】:swift json parse returning Optional快速 json 解析返回可选
【发布时间】:2018-05-08 20:07:28
【问题描述】:

我正在尝试快速解析 json 响应,并且很难做到这一点。当我引用 json 字符串的顶层并打印值时,我得到一个 Optional(<__nssingleobjectarrayi json>

当打印到控制台时,我得到:

Optional(<__NSSingleObjectArrayI 0x1c0014180>(
{
ack =     (
    Success
);
paginationOutput =     (
            {

然后是 json 的其余部分

我不知道可选项在做什么或为什么它在那里,但它似乎阻碍了我正在尝试做的其他解析,因为当我尝试进入嵌套值的下一个级别时,它总是返回无。

解析代码如下

URLSession.shared.dataTask(with: endpoint) { (data, response, error) in
        do {
            guard let data = data else {
                return
            }
            guard let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? NSDictionary else {
                return
            }

            //print(json)
            print(json.object(forKey: "findCompletedItemsResponse"))
            let dictionary1 = json.object(forKey: "findCompletedItemsResponse")

            print(dictionary1)
        } catch let error {
            print(error)
        }
        }.resume()

【问题讨论】:

  • 嗯,Optional 在您的对象的描述中,这是基本的 Swift(如何在 Swift 中处理 Optional)。我认为主要问题是dictionary1 实际上是Array,而不是Dictionary。一个只有一个对象的数组,它是一个字典,所以dictionary1 = json.object(forKey:"findCompletedItemsResponse").firstObject。此外,当等效项可用时,请避免使用 NSDictionary(所有 NSStuff)。
  • 是的,我一直在研究,但是如果我正确地遵循分解,在第一级之后会有一些项目被退回(对 json 来说相当新)。
  • 这里是在网络中运行请求时的响应视图code "findCompletedItemsResponse": { "xmlns": "http://www.marketplace.com/marketplace/search/v1/services", "ack": "Success", "version": "1.11.0", "timestamp": "2015-12-17T22:55:44.894Z", "searchResult": { "count": "2", "item": [ {

标签: json swift


【解决方案1】:

使用if-let 解包如下值:

if let dictionary1 = json.object(forKey: "findCompletedItemsResponse") {
print(dictionary1)
}

【讨论】:

    【解决方案2】:

    swift 中不需要.allowFragments

    如果你的json["findCompletedItemsResponse"]是字典类型,那么可以解析如下:

    URLSession.shared.dataTask(with: endpoint) { (data, response, error) in
        do {
            guard let data = data, let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] else {
                return
            }
    
            if let dictionary1 = json["findCompletedItemsResponse"] as? [String: Any] {
                 print(dictionary1)
            } else {
                print(json["findCompletedItemsResponse"])
            }
        } catch let error {
            print(error)
        }
        }.resume()
    

    【讨论】:

    • @ZackButcher,如果您没有在这里拿到您的字典,请告诉我print(json["findCompletedItemsResponse"]) 打印的内容。
    猜你喜欢
    • 2014-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多