【问题标题】:Rails JSON to Swift 2 JSONRails JSON 到 Swift 2 JSON
【发布时间】:2015-07-02 16:20:59
【问题描述】:

我正在尝试使用 JSON 将数据从我的 rails Web 服务器共享到 swift 应用程序。我正在努力建立这种联系。

来自 Rails 控制器:

    ...
    output = x.to_json
    render :json => output 
    ...

在 Swift iOS 应用中:

import UIKit
class FirstViewController: UIViewController {
override func viewDidLoad() {
    super.viewDidLoad()
    reachForWebsite()
}
override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
}
func reachForWebsite(){
    let url = NSURL(string: "myURL")
    let request = NSURLRequest(URL: url!)
    let task = NSURLSession.sharedSession().dataTaskWithURL(url!) {(data, response, error) in
        println(NSString(data: data!, encoding: NSUTF8StringEncoding))
        var error: NSError? = nil
        if let jsonObject = NSJSONSerialization.JSONObjectWithData(data!, options: nil, error = &error){
            if let dict = jsonObject as? NSDictionary {
                println(dict)
            } else {
                println("not a dictionary")
            }
        } else {
            println("Could not parse JSON: \(error!)")
        }
            println(data.dynamicType)
        }
    }
    task!.resume()
}
}

我可以验证我是否已成功接收数据,因为我可以将其转换为字符串并将其打印到应用程序的控制台。但是,我无法从中创建 NSDictionary 对象。错误随每个修补程序而变化,但与 Optionals 和 try catch 有关。

JSON

{"inside":[{"name":"BOB"}, ...],"outside":[{"name":"TIM","type":"HUMAN","id":1}, ...],"info":{"time":"2015-07-02"}}

【问题讨论】:

  • 你能发布一个你正在解析的 JSON 的例子吗?
  • 听起来您的 JSON 格式有问题,或者可能是数组而不是字典?此外,这可能是您正在寻找的答案的一部分,也可能不是,但这是一个用开关盒打开选项的好机会:gist.github.com/patricklynch/8d5b792c5fa2aad95fe7
  • @PatrickLynch 使用 JSON 格式更新问题
  • 不确定这是否会有所帮助,但请尝试使用此方法而不是 jsonObject 和 dict 行。不确定是否可行但值得一试 - 让 jsonresult:NSDictionary = 试试! NSJSONSerialization.JSONObjectWithData(self.bytes, options: NSJSONReadingOptions.MutableContainers) 一样! NSDictionary
  • self.bytes 在你的情况下是数据

标签: ruby-on-rails json swift swift2


【解决方案1】:

你为什么不试试这个用 Swift 2 解析 JSON

guard let task = NSURLSession.sharedSession().dataTaskWithURL(URL) {(data, response, error) in
guard let data = data, error == nil 
else 
{
    // Checks for errors if the task fails like for bad connectivity.
    print(error);
    return;
}
do 
{
    guard let JSONDict = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? [NSObject: AnyObject] 
    else
    {
        // The JSONDict wasn't a dictionary. Maybe its an array here? If it is change the structure of the parsing.
        print("The JSON wasn't a dictionary. Try array by optional casting to [AnyObject] instead of the cast above to [NSObject: AnyObject]")
        return
    }
    print("Parsed JSON successfully as dictionary: \(JSONDict)")
    // Do stuff with the JSONDict which is a Swift dictionary.
    // For example: let some = JSONDict["key"] as? ValueType will allow you to access the key of the JSONDict
}
catch 
{ 
    // JSON parsing error. 
    print(error) 
}
else 
{ 
     // Error task wasn't created that's unusual unless the URL was bad.
     // Fail here so that you can trace the stack and debug.
     assertionFailure();
}
task.resume()

如果它不起作用,请告诉我它在哪里失败以及打印到控制台的内容。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-11
    • 2015-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多