iOS - JSONSerialization VS JSONDecoder 和用法

iOS - JSONSerialization VS JSONDecoder and usage

所以我得到了关注 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" : 正确}

如果我这样做:

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