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

时间:2016-01-07 12:17:37

标签: json swift swift2 nsjsonserialization nsinputstream

我遇到了JSON问题。我通过互联网搜索,但没有找到任何适用于我的解决方案。

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

  

{ “数据”: “[{\” ID \ “:38,\” 名称\ “:\” 安东\ “},{\” ID \ “:160,\” 名称\ “:\” 克里斯托弗ETH \ “}]”}

我想解析数组,它以“数据”形式作为字符串发送。我试图从“数据”中获取String并在NSJSONSerialization中再次传递String。

这是正确的方法吗?

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
    }

1 个答案:

答案 0 :(得分:0)

不需要

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