gpt4 book ai didi

json - 在 Swift 3 中解析 Json 文件

转载 作者:搜寻专家 更新时间:2023-11-01 06:04:55 24 4
gpt4 key购买 nike

我想解析一个本地 JSON 文件,但我不知道如何在 Swift 3 中这样做

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

我一直收到这个错误:

'jsonObject' produces 'Any', not the expected contextual result type '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"
}
]

最佳答案

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

{ "blogs": [ { "id": 111, "url": "http://roadfiresoftware.com/blog/", "name": "Roadfire Software Blog" }, { "id": 345, "url": "https://developer.apple.com/swift/blog/", "name": "Swift Developer Blog" } ] }

关于json - 在 Swift 3 中解析 Json 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40144233/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com