【问题标题】:Parsing Json Files in Swift 3在 Swift 3 中解析 Json 文件
【发布时间】:2023-03-29 02:05:01
【问题描述】:

我想解析一个本地 JSON 文件,但我不知道如何在 Swift 3 中执行此操作

我当前的代码似乎不起作用

我不断收到此错误:

'jsonObject' 产生'Any',而不是预期的上下文结果类型'NSArray'

import UIKit
import Alamofire
import SwiftyJSON

class ViewController: UIViewController
{

    var allEntries: String!


    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func LoadAllQuestionsAndAnswers
    {
            let path = Bundle.main.path(forResource: "content", ofType: "json")
            let jsonData : NSData = NSData(contentsOfFile: path!)!
            allEntries = JSONSerialization.jsonObject(with: jsonData, options: JSONSerialization.ReadingOptions.mutableContainers, error: nil) as String
            NSLog(allEntries)
    }

}

我正在从这个 json 文件“content.json”加载数据

[
    {
        "id" : "1",
        "question": "What is the fastest fish in the ocean?",
             "answers": [
             "Sailfish",
             "Lion Fish",
             "Flounder",
             "Tiger Shark",
             "Swordfish"
            ],
         "difficulty": "1"
     },
     {
         "id" : "2",
         "question": "Which animal has the most legs?",
              "answers": [
              "Millipede",
              "Shrimp",
              "Octopus",
              "Dog",
              "Lion"
            ],
          "difficulty": "1"
     }
]

【问题讨论】:

  • 您使用的代码甚至无法编译,因为从 Swift 2 开始,此方法没有类似错误的参数,而是您需要使用 try catch 将其抛出。

标签: json swift parsing swift3 xcode8


【解决方案1】:
let path =  Bundle.main.path(forResource: "sample", ofType: "son")
 let jsonData = try? NSData(contentsOfFile: path!, options: NSData.ReadingOptions.mappedIfSafe) 
print(jsonData!) 
let jsonResult: NSDictionary = try! JSONSerialization.jsonObject(with: jsonData as! Data, options: JSONSerialization.ReadingOptions.mutableContainers) as! NSDictionary

// 将下面的示例json保存在一个文件中并命名为sample.json

{ “博客”:[ { “身份证”:111, "url": "http://roadfiresoftware.com/blog/", “名称”:“路火软件博客” }, { “身份证”:345, "url": "https://developer.apple.com/swift/blog/", "name": "Swift 开发者博客" } ] }

【讨论】:

    【解决方案2】:

    JSON 的根对象是一个数组

    var allEntries = [[String:Any]]()
    ...
    allEntries = try! JSONSerialization.jsonObject(with: jsonData, options: []) as! [[String:Any]]
    

    mutableContainers 在 Swift 中根本不需要

    【讨论】:

    • 感谢您的回复!我试过这个,它向我扔了一个箭头,我用[String:Any]而不是[[String:Any]],我能够得到回报
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-15
    • 1970-01-01
    • 2019-03-27
    相关资源
    最近更新 更多