iOS - JSONSerialization VS JSONDecoder 和使用

标签 ios json swift jsondecoder json-serialization

所以我得到了以下 json :

 {
"output": [
"{\"cameraIsOnboarded\" : true}"
 ],
"exit_code": 0
}

我试着用下面的模型解码它:

struct CameraOnboard: Codable {

  var output: [Output]
  //var exit_code: Int?
 }

struct Output: Codable {

  var cameraIsOnboarded: Bool?
}

然后在我的解析器中使用它:

        let infoString = try JSONDecoder().decode(CameraOnboard.self, from: data)

但它会崩溃。

然后我尝试使用 JSONSerialization,因为我认为\"cameraIsOnboarded\"键有问题,所以我从 alamofire 结果字符串中获取并尝试了以下操作:

   let jsonData = data.data(using: .utf8)

    var dic: [String : Any]?
    do {
        dic = try JSONSerialization.jsonObject(with: jsonData!, options: []) as? [String : Any]
    } catch {
        print(error.localizedDescription)
    }

    print(dic!)
    if let outPutArr  = dic?["output"] as? NSArray {
        print(outPutArr)

        if let first = outPutArr.firstObject {
            print(first)

            //let val =  first["cameraIsOnboarded"]
           // print(val!)
        }
    }

所以如上所述,我不知道如何提取值,但我打印:

{"cameraIsOnboarded": true}

如果我这样做:

  if let first = outPutArr.firstObject as? [String: Bool] {
            print(first)

            //let val =  first["cameraIsOnboarded"]
           // print(val!)
        }

它没有进去。

谢谢

最佳答案

json 应该是这样的(推荐)

{
    "output": {
        "cameraIsOnboarded" : true
    },
    "exit_code": 0
}

你可以用它来处理当前的情况

do {
   let  dic = try JSONSerialization.jsonObject(with: str.data(using: .utf8)!, options: []) as! [String : Any]
    if let outPutArr  = dic["output"] as? [String] {
         if let first = outPutArr.first {
           let dic = try JSONSerialization.jsonObject(with: (first as! String).data(using: .utf8)!, options: []) as! [String : Bool]
            print(dic["cameraIsOnboarded"])
        }
    } 
    } catch {
        print(error)
    }

关于iOS - JSONSerialization VS JSONDecoder 和使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53581328/

相关文章:

ios - 比较 NSString 与 NSString * const(在 iOS8.1 上)失败

ios - UIImagePickerController 没有出现在 xamarin iOS 中

ios - UIPageViewController 中包含的 ViewController 的委托(delegate)为零

c# - 具有相同属性名称但大小写不同的 Json 反序列化

ios - 使用 NSDictionary 访问 NSJSONSerialization 数据

ios - 关闭所有以前的 View Controller

ios - MapBox - 检测 zoomLevel 变化

javascript - 在 Twitter 应用程序书签中打开

objective-c - UITableViewCell 中的 UIButton subview 未按预期隐藏

sql - 如何在postgresql中将两行转换为键值json对象?