如何在swift 3中将jsonString转换为json字典?

时间:2018-02-20 04:27:16

标签: json swift

我有一个api,在解析json之后,响应得到如下所述,之后我也删除了斜线,但无法将其保存为字典格式,任何人都可以帮我解决这个问题吗?

这是我的代码

func productListSortDownloadJsonWithURL() {
        let url = URL(string: sortIndicesURL)!
        var request = URLRequest(url: url as URL)
        request.httpMethod = "GET"
        request.addValue("Basic Z29tZXRvb2FkOm55UWREZ1ZYMWdYU1FkMmhHWEpN", forHTTPHeaderField: "Authorization")
        let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
            if error != nil { print(error!); return }
            do {
                if let jsonObj = try! JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? String {
                    print(jsonObj)
                    self.secondIndices = jsonObj.replacingOccurrences(of:"\"", with: "")
                    DispatchQueue.main.async {

                    }
                }
            } catch {
                print(error)

            }
        }
        task.resume()
    }

这是我的json数据

  

" {\" 1 \":{\"属性\":\" price_index \" \"排序\":\"降序\" \" sortLabel \":\"最高           价格\"},\" 0 \":{\"属性\":\" price_index \" \"排序\":\" ASC \" \" sortLabel \":\"最低           价格\"},\" 2 \":{\"属性\":\" rating_summary \" \"排序\":\"降序\" \" sortLabel \":\"顶           额定\"}}"

2 个答案:

答案 0 :(得分:0)

swift 3.0

extension Data
{
func dataToJSON() -> Any? {
    do {
        return try JSONSerialization.jsonObject(with: self, options: .mutableContainers)
    } catch let myJSONError {
        print(myJSONError)
    }
    return nil
}
}

用法

if let dictResponse = data?.dataToJSON() as? NSDictionary {
 print(dictResponse)
} 

答案 1 :(得分:-1)

试试这个,

让yourDictionary = NSKeyedUnarchiver.unarchiveObject(with:data!)为?字典