如果我尝试将其转换为其他任何内容,则JSON Seralization返回nil

时间:2017-09-27 17:26:34

标签: json swift nsjsonserialization

我无法解析此json对象。我可以把它解析成Any。但是,如果我尝试将其作为NSDictionary或其他任何东西投射,则返回nil。谁能帮我?我咨询了几个问题,他们都给出了相同的结果。

    let task = URLSession.shared.dataTask(with: request) { data, response, error in
    if let reponse = response {
        print(reponse)
    }
    if let data = data {
        //print(data)

        do{

          //  let json = try JSONSerialization.jsonObject(with: data, options: [])


            let json = try JSONSerialization.jsonObject(with: data, options:.allowFragments)

                // do stuff here

            //  accountJson = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? NSDictionary

            print("\(json)") // This one prints .

            let accountJson = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? NSDictionary

            print("trying to print accountjson")
            print("\(accountJson)") // this one doesnt. 




        } catch {
            print(error)
        }

    }

}
task.resume()

第一个print语句有效,并在终端中生成以下代码。

(
    {
    "__v" = 0;
    "_id" = 59cba54406e2661530c1aa6e;
    pass = ra;
    type = ra;
    username = NikRa;
}
)

1 个答案:

答案 0 :(得分:0)

嗨,大家好我确实搞清楚了。我不得不把它作为一个数组内的数组。

let accountJson = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as?  [[String: Any]]