3

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

ironRoei
  • 2,049
  • 24
  • 45
  • 1
    Your JSON is weird. The value of `output` is an array of strings, not an array of dictionary. That's why your Codable attempt failed and why you are having trouble with JSONSerialization. – rmaddy Dec 02 '18 at 14:50
  • @rmaddy getting this JSON from the backend. with JSONSerialization i am not success to extract the bool – ironRoei Dec 02 '18 at 14:57
  • 1
    Your backend needs to fix the JSON. `"{\"cameraIsOnboarded\" : true}"` is a string, not a dictionary. It should be `{"cameraIsOnboarded" : true}` – rmaddy Dec 02 '18 at 14:59
  • @rmaddy i know , but till they do that, how can i handle that? – ironRoei Dec 02 '18 at 15:02
  • One way is to convert the string to Data and pass that data to JSONSerialization. – rmaddy Dec 02 '18 at 15:04

1 Answers1

3

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)
    }
Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87