解析 JSON 包含带 InputReader 的数组的字符串?

Parse JSON String which contains an array with InputReader?

我对 JSON 有疑问。我通过互联网搜索,但没有找到适合我的解决方案。

为了更好地工作,我将服务器的答案 (JSON) 保存在 *.json 文件中。 JSON 看起来像这样(短版):

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

我想解析在 "data" 中作为字符串发送的数组。我正在尝试从 "data" 中获取字符串并在 NSJSONSerialization.

中再次传递该字符串

这样对吗?

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
    }
不需要

NSStream,只需将 JSON 字符串转换为 NSData 并再次调用 JSONObjectWithData

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)
}