【问题标题】:Error Domain=NSCocoaErrorDomain Code=3840 “No value.” UserInfo={NSDebugDescription=No value.}错误域=NSCocoaErrorDomain 代码=3840 “无值。” UserInfo={NSDebugDescription=无值。}
【发布时间】:2016-04-06 21:02:55
【问题描述】:

我正在学习 JSON。我在从 URL 解析 JSON 时遇到问题。错误是“Error Domain=NSCocoaErrorDomain Code=3840 “No value.” UserInfo={NSDebugDescription=No value.}”

JSON 是有效的 - 我已经检查过了。这是 JSON 的结构:

[{"id":33,"name":"5","sort":2},{"id":34,"name":"6","sort":3},{"id":35,"name":"7","sortOrder":4}]

这是我的代码: 导入 UIKit

class ViewController: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()


    let urlAsString = "http://www.url.address/"
    let url = NSURL(string: urlAsString)!
    let urlSession = NSURLSession.sharedSession()
    let username = "admin"
    let password = "admin"

    struct Address {

        let name: String?
        let id: String?
        let sortOrder: String?

        init(dict: [String: AnyObject]) {

            name = dict["name"] as? String
            id = dict["id"] as? String
            sortOrder = dict["sort"] as? String
        }
    }
    let path = NSBundle.mainBundle().pathForResource("sections", ofType: "json")
    let jsonData = NSData()

    do {
        if let jsonDic = try NSJSONSerialization.JSONObjectWithData(jsonData,
            options: .MutableContainers) as? [String: AnyObject] {

                let addr = Address(dict: jsonDic)                    
                print("jsonDic")
        }

        } catch let error as NSError {
            print(error)
        }
}
func backButton(sender: AnyObject) {
    self.dismissViewControllerAnimated(true, completion: {})
}

}

【问题讨论】:

  • jsonData 是一个空的 NSData 对象。你能指望什么? - 开玩笑的,你必须从path获取数据
  • ... 并至少在类的顶层而不是在方法中声明模型结构

标签: ios json nsdata


【解决方案1】:

您需要实际上使用文件中的数据:

guard let path = NSBundle.mainBundle().pathForResource("sections", ofType: "json"), let jsonData = NSData(contentsOfFile: path) else { fatalError("Cannot find or load the sections file in the main bundle") } do { if let sections = try NSJSONSerialization.JSONObjectWithData(jsonData, options: .MutableContainers) as? [String: AnyObject] { // work with sections } ...

【讨论】:

  • 谢谢。但是现在我有错误“Thread 1:EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)”,代码为“fatalError("error")”。 Mayby 因为没有路径“部分”?我的 JSON 没有路径 - 只有我在第一个问题中提到的字符串。
  • 我看起来问题出在 NSBundle.mainBundle().pathForResource("sections", ofType: "json") - 如果没有路径“sections”,我应该如何更改 NSBundle?如果我把它留空 - pathForResource("", ofType: "json"),问题是一样的......
  • @Szekspir 一个简单的解决方法是将文件重命名为sections.json(如果您希望它只是json,则需要pathForResource("json", ofType:"")
  • 很遗憾,我无法重命名 JSON。所以我想我应该将 NSData 更改为 NSString。但后来我得到 Error Domain=NSCocoaErrorDomain Code=3840.
猜你喜欢
  • 1970-01-01
  • 2017-01-31
  • 1970-01-01
  • 2018-02-20
  • 1970-01-01
  • 2016-09-19
  • 1970-01-01
  • 1970-01-01
  • 2017-02-10
相关资源
最近更新 更多