在 Swift 4中将 Json 字符串转换为 Json 对象

我尝试将 JSON 字符串转换为 JSON 对象,但是在 JSONSerialization之后输出为 JSON 格式的 nil

回应字符串:

[{\"form_id\":3465,\"canonical_name\":\"df_SAWERQ\",\"form_name\":\"Activity 4 with Images\",\"form_desc\":null}]

我尝试用下面的代码转换这个字符串:

let jsonString = response.result.value
let data: Data? = jsonString?.data(using: .utf8)
let json = (try? JSONSerialization.jsonObject(with: data, options: [])) as? [String:AnyObject]
print(json ?? "Empty Data")
146955 次浏览

问题是你以为你的 jsonString 是字典,其实不是。

这是字典的 数组。 在原始 json 字符串中,数组以 [开头,字典以 {开头。


我使用了您的 json 字符串,代码如下:

let string = "[{\"form_id\":3465,\"canonical_name\":\"df_SAWERQ\",\"form_name\":\"Activity 4 with Images\",\"form_desc\":null}]"
let data = string.data(using: .utf8)!
do {
if let jsonArray = try JSONSerialization.jsonObject(with: data, options : .allowFragments) as? [Dictionary<String,Any>]
{
print(jsonArray) // use the json here
} else {
print("bad json")
}
} catch let error as NSError {
print(error)
}

我得到了结果:

[["form_desc": <null>, "form_name": Activity 4 with Images, "canonical_name": df_SAWERQ, "form_id": 3465]]

使用 JSONSerialization总是感觉笨拙和笨拙,但随着 Codable在 Swift 4中的到来更是如此。如果你在一个简单的 struct面前挥舞一个 [String:Any],它会... ... 疼。在操场上看看这个:

import Cocoa


let data = "[{\"form_id\":3465,\"canonical_name\":\"df_SAWERQ\",\"form_name\":\"Activity 4 with Images\",\"form_desc\":null}]".data(using: .utf8)!


struct Form: Codable {
let id: Int
let name: String
let description: String?


private enum CodingKeys: String, CodingKey {
case id = "form_id"
case name = "form_name"
case description = "form_desc"
}
}


do {
let f = try JSONDecoder().decode([Form].self, from: data)
print(f)
print(f[0])
} catch {
print(error)
}

用最小的努力处理这将感觉更加舒适。如果您的 JSON 不能正确解析,您将获得更多的信息。

我在这里尝试了解决方案,作为? [ String: AnyObject ]为我工作:

do{
if let json = stringToParse.data(using: String.Encoding.utf8){
if let jsonData = try JSONSerialization.jsonObject(with: json, options: .allowFragments) as? [String:AnyObject]{
let id = jsonData["id"] as! String
...
}
}
}catch {
print(error.localizedDescription)


}

我使用下面的代码,它的工作对我来说很好:

let jsonText = "{\"userName\":\"Bhavsang\"}"
var dictonary:NSDictionary?
    

if let data = jsonText.dataUsingEncoding(NSUTF8StringEncoding) {
        

do {
dictonary =  try NSJSONSerialization.JSONObjectWithData(data, options: [.allowFragments]) as? [String:AnyObject]
        

if let myDictionary = dictonary
{
print(" User name is: \(myDictionary["userName"]!)")
}
} catch let error as NSError {
            

print(error)
}
}
static func getJSONStringFromObject(object: Any?) -> String? {
do {
let jsonData = try JSONSerialization.data(withJSONObject: object ?? DUMMY_STRING, options: [])
return String(data: jsonData, encoding: .utf8) ?? DUMMY_STRING
} catch {
print(error.localizedDescription)
}
return DUMMY_STRING
}