【问题标题】:Convert Json string to Json object in Swift 4在 Swift 4 中将 Json 字符串转换为 Json 对象
【发布时间】:2017-11-14 08:54:43
【问题描述】:

我尝试将 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")

【问题讨论】:

  • 您是否添加了 alamofire 吊舱。 google.com/…
  • 是的,我安装了 Alamofire Pod
  • 改用do ... catch 并打印错误。它可能会告诉你出了什么问题。

标签: ios swift


【解决方案1】:

问题是你认为你的 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]]

【讨论】:

  • 我们如何从“jsonArray”中获取值。我正在尝试是否让 name = jsonArray["name"] as? String { // 没有错误 } 给出错误“Cannot subscript a value of type '[Dictionary]' with a index of type 'String'”
  • @Androidiseverythingforme :这是一个字典数组,试试let form_name = jsonArray[0]["form_name"] as? String,你会得到输出。
【解决方案2】:

使用JSONSerialization 总是感觉不灵活和笨拙,但随着Codable 在Swift 4 中的到来更是如此。如果你在简单的struct 前面使用[String:Any],它将...伤害。在 Playground 中查看:

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 解析不正确,您将获得更多信息。

【讨论】:

  • 我是唯一一个得到“Type 'Form' does not conform to protocol 'Decodable'”的人吗?
  • 您必须发布您的代码(在另一个问题中,而不是评论,那里看起来很糟糕)和您的 Swift 版本,以便任何人提供帮助。
  • 删除 Swift 5 的“import Cocoa”然后它就可以工作了。谢谢!
【解决方案3】:

我在这里尝试了解决方案,作为? [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)

}

【讨论】:

  • id 对我来说是零。
【解决方案4】:

我使用了下面的代码,它对我来说工作正常。 :

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)
         }
}

【讨论】:

    【解决方案5】:
    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
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-08-24
      • 2019-08-27
      • 2020-05-27
      • 1970-01-01
      • 1970-01-01
      • 2021-10-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多