Reputation: 2209
So i am getting the follow json :
{
"output": [
"{\"cameraIsOnboarded\" : true}"
],
"exit_code": 0
}
i tried to decode it with the model below:
struct CameraOnboard: Codable {
var output: [Output]
//var exit_code: Int?
}
struct Output: Codable {
var cameraIsOnboarded: Bool?
}
And then use it in my parser :
let infoString = try JSONDecoder().decode(CameraOnboard.self, from: data)
but it craches.
Then i have tried to use JSONSerialization because i thought i have a problem with the \"cameraIsOnboarded\" key, so i got from alamofire result string and tried the follow:
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!)
}
}
so as above i dont no how to extract the value yet i print :
{"cameraIsOnboarded" : true}
if i do as follow:
if let first = outPutArr.firstObject as? [String: Bool] {
print(first)
//let val = first["cameraIsOnboarded"]
// print(val!)
}
it dosent step inside.
Thanks
Upvotes: 3
Views: 3106
Reputation: 100503
The json should look like ( Recommended)
{
"output": {
"cameraIsOnboarded" : true
},
"exit_code": 0
}
You can use this to handle current case
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)
}
Upvotes: 3