gpt4 book ai didi

iOS - JSONSerialization VS JSONDecoder 和使用

转载 作者:搜寻专家 更新时间:2023-11-01 06:55:37 25 4
gpt4 key购买 nike

所以我得到了以下 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com