jsonswiftswift2nsjsonserializationnsinputstream

Parse JSON String which contains an array with InputReader?


I have a problem with JSON. I searched through Internet, but didn't found any solution that worked for me.

For better working I saved the answer (JSON) of the server in a *.json file. The JSON is looking like this (short version):

{"data":"[{\"id\":38,\"name\":\"Anton\"},{\"id\":160,\"name\":\"Christopher Eth\"}]"}

I want to parse the Array, which is sent in "data" as a String. I am trying to get the String out of "data" and pass the String again in the NSJSONSerialization.

Is that the right way?

guard let path = NSBundle.mainBundle().pathForResource("names", ofType: "json") else {
        print("Error finding File")
        return
    }

    do {
        let data:NSData? = NSData(contentsOfFile: path)

        if let jsonResult =
            try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as? NSDictionary {
                let result = jsonResult["data"]
                if(result == nil){
                    print("error")
                }else{
                    //How can I convert the result! to an Stream to pass it to the JSONSerialization???
                    let stream = NSInputStream(/*result!*/)
                    let resultArray = try NSJSONSerialization.JSONObjectWithStream(stream: stream, options: NSJSONReadingOptions.MutableContainers) as? NSArray{
                    //Do something with array
                }

    }catch let error as NSError{
        print("Error: \(error)")
        return
    }

Solution

  • NSStream is not needed, just convert the JSON string into NSData and call JSONObjectWithData a second time.

    guard let url = NSBundle.mainBundle().URLForResource("names", withExtension: "json"), jsonData = NSData(contentsOfURL: url) else {
      print("Error finding File")
      return
    }
    do {
      let names = try NSJSONSerialization.JSONObjectWithData(jsonData, options: []) as! [String:AnyObject]
      if let jsonResult = names["data"] {
        let nameData = jsonResult.dataUsingEncoding(NSUTF8StringEncoding)!
        let resultArray = try NSJSONSerialization.JSONObjectWithData(nameData, options: .MutableContainers) as! [[String:AnyObject]]
        for item in resultArray {
          print(item["name"]!, item["id"]!)
        }
      } else {
        print("error")
      }
    } catch let  error as NSError {
      print(error)
    }