所以我得到以下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)
}