使用Swift读取JSON文件


205

我真的很努力地尝试将JSON文件读入Swift,以便可以使用它。我花了两天的大部分时间来重新搜索并尝试不同的方法,但到目前为止还没有运气,因此我已经注册了StackOverFlow,以查看是否有人可以向我指出正确的方向.....

我的JSON文件称为test.json,其中包含以下内容:

{
  "person":[
     {
       "name": "Bob",
       "age": "16",
       "employed": "No"
     },
     {
       "name": "Vinny",
       "age": "56",
       "employed": "Yes"
     }
  ]
}    

该文件直接存储在文档中,我使用以下代码进行访问:

let file = "test.json"
let dirs : String[] = NSSearchPathForDirectoriesInDomains(
                                                          NSSearchpathDirectory.DocumentDirectory,
                                                          NSSearchPathDomainMask.AllDomainMask,
                                                          true) as String[]

if (dirs != nil) {
    let directories: String[] = dirs
    let dir = directories[0]
    let path = dir.stringByAppendingPathComponent(file)
}

var jsonData = NSData(contentsOfFile:path, options: nil, error: nil)
println("jsonData \(jsonData)" // This prints what looks to be JSON encoded data.

var jsonDict = NSJSONSerialization.JSONObjectWithData(jsonData, options: nil, error: nil) as? NSDictionary

println("jsonDict \(jsonDict)") - This prints nil..... 

如果有人可以在正确的方向上向我推销我如何反序列化JSON文件并将其放在可访问的Swift对象中,我将万分感谢!

亲切的问候,

Krivvenz。


1
使用错误参数...
Matthias Bauch 2014年

2
请发布实际的可编译代码。到目前为止,path仅在if作用域中可见,而在中使用时则无法解析NSData(contentsOfFile, options, error)。枚举名称中也有错字。
Kreiri 2014年

1
我的API已针对Swift 3进行了全面更新:github.com/borchero/WebParsing
borchero 16/09/29

这是关键->“ values”:“来自tmclass.json文件%的%LOAD VALUE”,我需要从文件中解析另一个JSON,然后如何在SWIFT中实现呢?
Mayur Shinde

Answers:


287

请遵循以下代码:

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
      }
}

4
如果您解释了为什么/如何解决问题中所描述的问题,而不是仅仅提供一堆代码,那将更有帮助。
Martin R

您好Abhishek-感谢您的回答,但仍然无法正常工作。这会导致应用程序崩溃并显示以下错误:2014-06-25 16:02:04.146 H&S Capture [4937:131932] ***由于未捕获的异常'NSInvalidArgumentException'而终止应用程序,原因:'***- [_NSPlaceholderData initWithContentsOfFile:options:error:]:无文件参数'***第一次抛出调用堆栈:关于这的任何想法?对于jsonData选项:我放置了(路径,选项:NSDataReadingOptions.DataReadingMappedIfSafe,错误:无)
Krivvenz 2014年

您的文件路径不正确。显然,在您指定的路径上没有名为test.json的文件。请检查文件的正确位置
Abhishek 2014年

15
“让jsonData = NSData的(contentsOfFile:路径!)”而不是“让jsonData = NSData.dataWithContentsOfFile(路径选择:.DataReadingMappedIfSafe,错误:无)”

7
最好还是在这里使用警卫其他声明,而不要使用这个厄运金字塔。
Zonily Jame'2

140

如果有人在寻找SwiftyJSON答案:
更新:
对于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.")
}

2
这使我转向了swiftyJSON和迦太基!谢谢:)
Paul Wand 2015年

我只是用它来发现它缺少对象映射,下一次我将尝试使用另一个库
Elazaron

为了避免在swift 3中出现复制粘贴错误,NSData和NSError变成了Data and Error。
瑟瓦

我尝试了几种不同的方法和这个工作对我最好的斯威夫特卡伦特3
crobicha

(!)由于MacOS的10.6 / iOS 4的有一个API url(forResource(NS)Bundle,以避免额外的步骤来创建网址
vadian

102

使用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
}

9
应将其移至新的文档功能,或标记为正确答案。
系统

24

Xcode 8 Swift 3从文件更新读取json:

    if let path = Bundle.main.path(forResource: "userDatabseFakeData", ofType: "json") {
        do {
            let jsonData = try NSData(contentsOfFile: path, options: NSData.ReadingOptions.mappedIfSafe)
            do {
                let jsonResult: NSDictionary = try JSONSerialization.jsonObject(with: jsonData as Data, options: JSONSerialization.ReadingOptions.mutableContainers) as! NSDictionary
                if let people : [NSDictionary] = jsonResult["person"] as? [NSDictionary] {
                    for person: NSDictionary in people {
                        for (name,value) in person {
                            print("\(name) , \(value)")
                        }
                    }
                }
            } catch {}
        } catch {}
    }

14

更新了Swift 3.0的名称

基于Abhishek的答案Druva的答案

func loadJson(forFilename fileName: String) -> NSDictionary? {

    if let url = Bundle.main.url(forResource: fileName, withExtension: "json") {
        if let data = NSData(contentsOf: url) {
            do {
                let dictionary = try JSONSerialization.jsonObject(with: data as Data, options: .allowFragments) as? NSDictionary

                return dictionary
            } catch {
                print("Error!! Unable to parse  \(fileName).json")
            }
        }
        print("Error!! Unable to load  \(fileName).json")
    }

    return nil
}

12

简化Peter Kreinz提供的示例。适用于Swift 4.2。

扩展功能:

extension Decodable {
  static func parse(jsonFile: String) -> Self? {
    guard let url = Bundle.main.url(forResource: jsonFile, withExtension: "json"),
          let data = try? Data(contentsOf: url),
          let output = try? JSONDecoder().decode(self, from: data)
        else {
      return nil
    }

    return output
  }
}

示例模型:

struct Service: Decodable {
  let name: String
}

用法示例:

/// service.json
/// { "name": "Home & Garden" }

guard let output = Service.parse(jsonFile: "service") else {
// do something if parsing failed
 return
}

// use output if all good

该示例也适用于数组:

/// services.json
/// [ { "name": "Home & Garden" } ]

guard let output = [Service].parse(jsonFile: "services") else {
// do something if parsing failed
 return
}

// use output if all good

注意,我们如何不提供任何不必要的泛型,因此我们不需要转换分析结果。


10

Swift 2.1答案(基于Abhishek的答案):

    if let path = NSBundle.mainBundle().pathForResource("test", ofType: "json") {
        do {
            let jsonData = try NSData(contentsOfFile: path, options: NSDataReadingOptions.DataReadingMappedIfSafe)
            do {
                let jsonResult: NSDictionary = try NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary
                if let people : [NSDictionary] = jsonResult["person"] as? [NSDictionary] {
                    for person: NSDictionary in people {
                        for (name,value) in person {
                            print("\(name) , \(value)")
                        }
                    }
                }
            } catch {}
        } catch {}
    }

10

Swift 3.0,Xcode 8,iOS 10

 if let path = Bundle.main.url(forResource: "person", withExtension: "json") {

        do {
            let jsonData = try Data(contentsOf: path, options: .mappedIfSafe)
            do {
                if let jsonResult = try JSONSerialization.jsonObject(with: jsonData, options: JSONSerialization.ReadingOptions(rawValue: 0)) as? NSDictionary {
                    if let personArray = jsonResult.value(forKey: "person") as? NSArray {
                        for (_, element) in personArray.enumerated() {
                            if let element = element as? NSDictionary {
                                let name = element.value(forKey: "name") as! String
                                let age = element.value(forKey: "age") as! String
                                let employed = element.value(forKey: "employed") as! String
                                print("Name: \(name),  age: \(age), employed: \(employed)")
                            }
                        }
                    }
                }
            } catch let error as NSError {
                print("Error: \(error)")
            }
        } catch let error as NSError {
            print("Error: \(error)")
        }
    }

输出:

Name: Bob,  age: 16, employed: No
Name: Vinny,  age: 56, employed: Yes


7

这是我使用SwiftyJSON的解决方案

if let path : String = NSBundle.mainBundle().pathForResource("filename", ofType: "json") {
    if let data = NSData(contentsOfFile: path) {

        let json = JSON(data: data)

    }
}

7
fileprivate class BundleTargetingClass {}
func loadJSON<T>(name: String) -> T? {
  guard let filePath = Bundle(for: BundleTargetingClass.self).url(forResource: name, withExtension: "json") else {
    return nil
  }

  guard let jsonData = try? Data(contentsOf: filePath, options: .mappedIfSafe) else {
    return nil
  }

  guard let json = try? JSONSerialization.jsonObject(with: jsonData, options: .allowFragments) else {
    return nil
  }

  return json as? T
}

👆🏻复制粘贴就绪,第三方框架独立解决方案。

用法👇🏻

let json:[[String : AnyObject]] = loadJSON(name: "Stations")!


这对我有用。我需要将可搜索的药物列表硬编码到应用程序中。我从mySQL数据库中获取了json文件。我将json文件放到在viewDidLoad和bam中运行的XCODE项目中,我有了json字典!
布莱恩(Brian

5

我提供了另一个答案,因为这里没有一个适合从测试包中加载资源。如果您使用的是发布JSON的远程服务,并且希望对测试结果进行单元测试而不点击实际服务,则可以获取一个或多个响应,并将其放入项目的Tests文件夹中的文件中。

func testCanReadTestJSONFile() {
    let path = NSBundle(forClass: ForecastIOAdapterTests.self).pathForResource("ForecastIOSample", ofType: "json")
    if let jsonData = NSData(contentsOfFile:path!) {
        let json = JSON(data: jsonData)
        if let currentTemperature = json["currently"]["temperature"].double {
            println("json: \(json)")
            XCTAssertGreaterThan(currentTemperature, 0)
        }
    }
}

这也使用SwiftyJSON,但获取测试包并加载文件的核心逻辑是问题的答案。


5

斯威夫特4:尝试我的解决方案:

test.json

{
    "person":[
        {
            "name": "Bob",
            "age": "16",
            "employed": "No"
        },
        {
            "name": "Vinny",
            "age": "56",
            "employed": "Yes"
        }
    ]
}

RequestCodable.swift

import Foundation

struct RequestCodable:Codable {
    let person:[PersonCodable]
}

人可编码

import Foundation

struct PersonCodable:Codable {
    let name:String
    let age:String
    let employed:String
}

Decodable + FromJSON.swift

import Foundation

extension Decodable {

    static func fromJSON<T:Decodable>(_ fileName: String, fileExtension: String="json", bundle: Bundle = .main) throws -> T {
        guard let url = bundle.url(forResource: fileName, withExtension: fileExtension) else {
            throw NSError(domain: NSURLErrorDomain, code: NSURLErrorResourceUnavailable)
        }

        let data = try Data(contentsOf: url)

        return try JSONDecoder().decode(T.self, from: data)
    }
}

例:

let result = RequestCodable.fromJSON("test") as RequestCodable?

result?.person.compactMap({ print($0) }) 

/*
PersonCodable(name: "Bob", age: "16", employed: "No")
PersonCodable(name: "Vinny", age: "56", employed: "Yes")
*/

1
您的fromJSON扩展函数将引发,但是在示例中,您在没有try关键字的情况下调用了它。此代码将无法编译。
NeverwinterMoon

另外,由于fromJSON您使用的是Decodable扩展名,但是您不使用来自Decodable类型的任何信息,而是提供其他(完全无用)的泛型。
NeverwinterMoon

3

最新的Swift 3.0绝对有效

func loadJson(filename fileName: String) -> [String: AnyObject]?
{
    if let url = Bundle.main.url(forResource: fileName, withExtension: "json") 
{
      if let data = NSData(contentsOf: url) {
          do {
                    let object = try JSONSerialization.jsonObject(with: data as Data, options: .allowFragments)
                    if let dictionary = object as? [String: AnyObject] {
                        return dictionary
                    }
                } catch {
                    print("Error!! Unable to parse  \(fileName).json")
                }
            }
            print("Error!! Unable to load  \(fileName).json")
        }
        return nil
    }

3

斯威夫特4 JSONClassDecodable -为那些喜欢谁班

如下定义类:

class People: Decodable {
  var person: [Person]?

  init(fileName : String){
    // url, data and jsonData should not be nil
    guard let url = Bundle.main.url(forResource: fileName, withExtension: "json") else { return }
    guard let data = try? Data(contentsOf: url) else { return }
    guard let jsonData = try? JSONDecoder().decode(People.self, from: data) else { return }

    // assigns the value to [person]
    person = jsonData.person
  }
}

class Person : Decodable {
  var name: String
  var age: String
  var employed: String
}

用法,非常抽象:

let people = People(fileName: "people")
let personArray = people.person

这允许同时用于类PeoplePerson类的方法,变量(属性)和方法也可以private根据需要进行标记。


3

以下代码对我有用。我正在使用Swift 5

let path = Bundle.main.path(forResource: "yourJSONfileName", ofType: "json")
var jsonData = try! String(contentsOfFile: path!).data(using: .utf8)!

然后,如果您的“人员结构”(或类)是可分解的(及其所有属性),则可以简单地执行以下操作:

let person = try! JSONDecoder().decode(Person.self, from: jsonData)

我避免了所有错误处理代码,以使代码更清晰易读。


2

以最安全的方式更新了Swift 3

    private func readLocalJsonFile() {

    if let urlPath = Bundle.main.url(forResource: "test", withExtension: "json") {

        do {
            let jsonData = try Data(contentsOf: urlPath, options: .mappedIfSafe)

            if let jsonDict = try JSONSerialization.jsonObject(with: jsonData, options: .mutableContainers) as? [String: AnyObject] {

                if let personArray = jsonDict["person"] as? [[String: AnyObject]] {

                    for personDict in personArray {

                        for (key, value) in personDict {

                            print(key, value)
                        }
                        print("\n")
                    }
                }
            }
        }

        catch let jsonError {
            print(jsonError)
        }
    }
}

在此处输入图片说明


2

Swift 5.1,Xcode 11

您可以使用此:


struct Person : Codable {
    let name: String
    let lastName: String
    let age: Int
}

func loadJson(fileName: String) -> Person? {
   let decoder = JSONDecoder()
   guard
        let url = Bundle.main.url(forResource: fileName, withExtension: "json"),
        let data = try? Data(contentsOf: url),
        let person = try? decoder.decode(Class.self, from: data)
   else {
        return nil
   }

   return person
}

1

根据Abhishek的答案,对于iOS 8,这将是:

let masterDataUrl: NSURL = NSBundle.mainBundle().URLForResource("masterdata", withExtension: "json")!
let jsonData: NSData = NSData(contentsOfURL: masterDataUrl)!
let jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(jsonData, options: nil, error: nil) as! NSDictionary
var persons : NSArray = jsonResult["person"] as! NSArray

您正在使用Swift 2.0吗?然后是的。2.0之前已回答此问题。
David Poxon '16

1

这适用于XCode 8.3.3

func fetchPersons(){

    if let pathURL = Bundle.main.url(forResource: "Person", withExtension: "json"){

        do {

            let jsonData = try Data(contentsOf: pathURL, options: .mappedIfSafe)

            let jsonResult = try JSONSerialization.jsonObject(with: jsonData, options: .mutableContainers) as! [String: Any]
            if let persons = jsonResult["person"] as? [Any]{

                print(persons)
            }

        }catch(let error){
            print (error.localizedDescription)
        }
    }
}

1

Swift 4.1更新了Xcode 9.2

if let filePath = Bundle.main.path(forResource: "fileName", ofType: "json"), let data = NSData(contentsOfFile: filePath) {

     do {
      let json = try JSONSerialization.jsonObject(with: data as Data, options: JSONSerialization.ReadingOptions.allowFragments)        
        }
     catch {
                //Handle error
           }
 }

3
没有什么新的,恰恰相反:不要NSData在Swift 3+中使用,.allowFragments在这种情况下毫无意义。
vadian '18

1
//change type based on your struct and right JSON file

let quoteData: [DataType] =
    load("file.json")

func load<T: Decodable>(_ filename: String, as type: T.Type = T.self) -> T {
    let data: Data

    guard let file = Bundle.main.url(forResource: filename, withExtension: nil)
        else {
            fatalError("Couldn't find \(filename) in main bundle.")
    }

    do {
        data = try Data(contentsOf: file)
    } catch {
        fatalError("Couldn't load \(filename) from main bundle:\n\(error)")
    }

    do {
        let decoder = JSONDecoder()
        return try decoder.decode(T.self, from: data)
    } catch {
        fatalError("Couldn't parse \(filename) as \(T.self):\n\(error)")
    }
}


0

我已使用以下代码从项目目录中存在的FAQ-data.json文件中获取JSON

我正在使用Swift在Xcode 7.3中实现。

     func fetchJSONContent() {
            if let path = NSBundle.mainBundle().pathForResource("FAQ-data", ofType: "json") {

                if let jsonData = NSData(contentsOfFile: path) {
                    do {
                        if let jsonResult: NSDictionary = try NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.MutableContainers) as? NSDictionary {

                            if let responseParameter : NSDictionary = jsonResult["responseParameter"] as? NSDictionary {

                                if let response : NSArray = responseParameter["FAQ"] as? NSArray {
                                    responseFAQ = response
                                    print("response FAQ : \(response)")
                                }
                            }
                        }
                    }
                    catch { print("Error while parsing: \(error)") }
                }
            }
        }

override func viewWillAppear(animated: Bool) {
        fetchFAQContent()
    }

JSON文件的结构:

{
    "status": "00",
    "msg": "FAQ List ",
    "responseParameter": {
        "FAQ": [
            {                
                "question":Question No.1 here”,
                "answer":Answer goes here”,  
                "id": 1
            },
            {                
                "question":Question No.2 here”,
                "answer":Answer goes here”,
                "id": 2
            }
            . . .
        ]
    }
}

0

我可能还会推荐Ray Wenderlich的Swift JSON教程(它也涵盖了很棒的SwiftyJSON替代品Gloss)。摘录(摘录(其本身并不能完全回答发布者,但是此答案的附加价值是链接,因此请不要为-1)):

在Objective-C中,解析和反序列化JSON非常简单:

NSArray *json = [NSJSONSerialization JSONObjectWithData:JSONData
options:kNilOptions error:nil];
NSString *age = json[0][@"person"][@"age"];
NSLog(@"Dani's age is %@", age);

在Swift中,由于Swift的可选内容和类型安全性,解析和反序列化JSON有点麻烦。但是作为Swift 2.0的一部分,guard引入了该语句来帮助摆脱嵌套if语句:

var json: Array!
do {
  json = try NSJSONSerialization.JSONObjectWithData(JSONData, options: NSJSONReadingOptions()) as? Array
} catch {
  print(error)
}

guard let item = json[0] as? [String: AnyObject],
  let person = item["person"] as? [String: AnyObject],
  let age = person["age"] as? Int else {
    return;
}
print("Dani's age is \(age)")

当然,在XCode 8.x中,只需双击空格键,然后说:“嘿,Siri,请在Swift 3.0中为我反序列化此JSON,并带有空格/制表符。”


0

SWIFTYJSON版本SWIFT 3

func loadJson(fileName: String) -> JSON {

    var dataPath:JSON!

    if let path : String = Bundle.main.path(forResource: fileName, ofType: "json") {
        if let data = NSData(contentsOfFile: path) {
             dataPath = JSON(data: data as Data)
        }
    }
    return dataPath
}

0

首先创建一个Struc编码,如下所示:

  struct JuzgadosList : Codable {
    var CP : Int
    var TEL : String
    var LOCAL : String
    var ORGANO : String
    var DIR : String
}

现在声明变量

 var jzdosList = [JuzgadosList]()

从主目录读取

func getJsonFromDirectory() {

        if let path = Bundle.main.path(forResource: "juzgados", ofType: "json") {
            do {
                let data = try Data(contentsOf: URL(fileURLWithPath: path), options: .alwaysMapped)
                let jList = try JSONDecoder().decode([JuzgadosList].self, from: data)
                self.jzdosList = jList

                DispatchQueue.main.async() { () -> Void in
                    self.tableView.reloadData()
                }

            } catch let error {
                print("parse error: \(error.localizedDescription)")
            }
        } else {
            print("Invalid filename/path.")
        }
    }

从网上阅读

func getJsonFromUrl(){

        self.jzdosList.removeAll(keepingCapacity: false)

        print("Internet Connection Available!")

        guard let url = URL(string: "yourURL")  else { return }

        let request = URLRequest(url: url, cachePolicy: URLRequest.CachePolicy.reloadIgnoringLocalCacheData, timeoutInterval: 60.0)
        URLSession.shared.dataTask(with: request) { (data, response, err) in
            guard let data = data else { return }
            do {
                let jList = try JSONDecoder().decode([JuzgadosList].self, from: data)
                self.jzdosList = jList

                DispatchQueue.main.async() { () -> Void in
                    self.tableView.reloadData()
                }
            } catch let jsonErr {
                print("Error serializing json:", jsonErr)
            }
        }.resume()
    }

0

使用此通用功能

func readJSONFromFile<T: Decodable>(fileName: String, type: T.Type) -> T? {
    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(T.self, from: data)
            return jsonData
        } catch {
            print("error:\(error)")
        }
    }
    return nil
}

这段代码:

let model = readJSONFromFile(fileName: "Model", type: Model.self)

对于这种类型:

struct Model: Codable {
    let tall: Int
}
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.