3 回答

TA貢獻1712條經驗 獲得超3個贊
請遵循以下代碼:
if let path = NSBundle.mainBundle().pathForResource("test", ofType: "json")
{
if let jsonData = NSData(contentsOfFile: path, options: .DataReadingMappedIfSafe, error: nil)
{
if let jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.MutableContainers, error: nil) as? NSDictionary
{
if let persons : NSArray = jsonResult["person"] as? NSArray
{
// Do stuff
}
}
}
}
數組“人員”將包含關鍵人員的所有數據。遍歷以獲取它。
Swift 4.0:
if let path = Bundle.main.path(forResource: "test", ofType: "json") {
do {
let data = try Data(contentsOf: URL(fileURLWithPath: path), options: .mappedIfSafe)
let jsonResult = try JSONSerialization.jsonObject(with: data, options: .mutableLeaves)
if let jsonResult = jsonResult as? Dictionary<String, AnyObject>, let person = jsonResult["person"] as? [Any] {
// do stuff
}
} catch {
// handle error
}
}

TA貢獻1796條經驗 獲得超10個贊
更新:
對于Swift 3/4:
if let path = Bundle.main.path(forResource: "assets/test", ofType: "json") {
? ? do {
? ? ? ? let data = try Data(contentsOf: URL(fileURLWithPath: path), options: .alwaysMapped)
? ? ? ? let jsonObj = try JSON(data: data)
? ? ? ? print("jsonData:\(jsonObj)")
? ? } catch let error {
? ? ? ? print("parse error: \(error.localizedDescription)")
? ? }
} else {
? ? print("Invalid filename/path.")
}

TA貢獻1775條經驗 獲得超11個贊
使用Decodable的Swift 4
struct ResponseData: Decodable {
var person: [Person]
}
struct Person : Decodable {
var name: String
var age: String
var employed: String
}
func loadJson(filename fileName: String) -> [Person]? {
if let url = Bundle.main.url(forResource: fileName, withExtension: "json") {
do {
let data = try Data(contentsOf: url)
let decoder = JSONDecoder()
let jsonData = try decoder.decode(ResponseData.self, from: data)
return jsonData.person
} catch {
print("error:\(error)")
}
}
return nil
}
迅捷3
func loadJson(filename fileName: String) -> [String: AnyObject]? {
if let url = Bundle.main.url(forResource: fileName, withExtension: "json") {
do {
let data = try Data(contentsOf: url)
let object = try JSONSerialization.jsonObject(with: data, options: .allowFragments)
if let dictionary = object as? [String: AnyObject] {
return dictionary
}
} catch {
print("Error!! Unable to parse \(fileName).json")
}
}
return nil
}
- 3 回答
- 0 關注
- 867 瀏覽
添加回答
舉報