ios 在 Swift 4 中将 Json 字符串转换为 Json 对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/47281375/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert Json string to Json object in Swift 4
提问by Inderpal Singh
I try to convert JSON string to a JSON object but after JSONSerialization
the output is nil
in JSON.
我尝试将 JSON 字符串转换为 JSON 对象,但在JSONSerialization
输出为nil
JSON 之后。
Response String:
响应字符串:
[{\"form_id\":3465,\"canonical_name\":\"df_SAWERQ\",\"form_name\":\"Activity 4 with Images\",\"form_desc\":null}]
I try to convert this string with my code below:
我尝试使用下面的代码转换此字符串:
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")
回答by Amit
The problem is that you thought your jsonString is a dictionary. It's not.
问题是你认为你的 jsonString 是一本字典。它不是。
It's an arrayof dictionaries.
In raw json strings, arrays begin with [
and dictionaries begin with {
.
这是一个字典数组。在原始 json 字符串中,数组以 开头,[
字典以 开头{
。
I used your json string with below code :
我将您的 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)
}
and I am getting the output :
我得到了输出:
[["form_desc": <null>, "form_name": Activity 4 with Images, "canonical_name": df_SAWERQ, "form_id": 3465]]
回答by Patru
Using JSONSerialization
always felt unSwifty and unwieldy, but it is even more so with the arrival of Codable
in Swift 4. If you wield a [String:Any]
in front of a simple struct
it will ... hurt. Check out this in a Playground:
使用JSONSerialization
总是感觉不灵活和笨拙,但随着Codable
Swift 4的到来更是如此。如果你[String:Any]
在一个简单的前面使用struct
它会......伤害。在操场上看看这个:
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)
}
With minimal effort handling this will feel a whole lot more comfortable. Andyou are given a lot more information if your JSON does not parse properly.
用最少的努力处理这会感觉更舒服。如果您的 JSON 解析不正确,您将获得更多信息。
回答by Aviram Netanel
I tried the solutions here, and as? [String:AnyObject]worked for me:
我在这里尝试了解决方案,作为?[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)
}
回答by Zain Anjum
func convertToDictionary(text: String) -> [String: Any]? {
if let data = text.data(using: .utf8) {
do {
return try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
} catch {
print(error.localizedDescription)
}
}
return nil
}
let str = "{\"name\":\"James\"}"
let dict = convertToDictionary(text: str)
回答by Bhavsang Jam
I used below code and it's working fine for me. :
我使用了下面的代码,它对我来说很好用。:
let jsonText = "{\"userName\":\"Bhavsang\"}" var dictonary:NSDictionary?
让 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)
}
}