没有获得在Swift中解析JSON的预期结果

时间:2017-05-04 00:47:14

标签: json swift

我有一个看起来像这样的网络服务

func downloadJsonWithUrl()
{
    let url = URL(string:"weserviceurl")

    let task = URLSession.shared.dataTask(with: url!) { (data, response, error) in
        if error != nil
        {
            print("Error")
        }
        else
        {
            if let content = data
            {
                do
                {
                    let myJson = try JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject
                   print(myJson)
                }
                catch
                {
                }
            }
        }
    }
    task.resume()
}

我使用此代码读取程序中的json:

if let info = myJson as? NSArray
{
    if let categories = info["title"]
    {
        print(categories)
    }
}

我的问题是,目前使用此序列化下面的代码:

inout

不起作用。它返回空。为什么?

2 个答案:

答案 0 :(得分:1)

试试这个

func downloadJsonWithUrl() {
  let url = URL(string:"link")

  let task = URLSession.shared.dataTask(with: url!) { (data, response, error) in
        if error != nil {
            print("Error")
        } else {
            if let content = data {
                do {
                    let myJson = try JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers) as! [AnyObject]
                    var categories: [String] = []

                    for item in myJson {
                        categories.append(item["title"] as! String)
                    }
                    print(categories)
                } catch {
                    print(error)
                }
            }
        }
    }
    task.resume()
}

答案 1 :(得分:0)

您应该使用swift ArrayDictionary类型。例如,... as? [[String: Any]]表示您期待一系列字典:

let task = URLSession.shared.dataTask(with: url!) { data, response, error in
    guard let data = data, error == nil else {
        print("\(error)")
        return
    }

    guard let json = try? JSONSerialization.jsonObject(with: data), let array = json as? [[String: Any]] else {
        print("not JSON array of dictionaries")
        return
    }

    for dictionary in array {
        if let idTest = dictionary["id_test"], let title = dictionary["title"] {
            print("\(idTest): \(title)")
        }
    }
}