【问题标题】:read/write local json file swift 4读/写本地json文件swift 4
【发布时间】:2018-12-06 15:39:46
【问题描述】:

请帮帮我! 我在项目中添加了一个 json 文件 我的 json 文件:

{
  "person": [
    {
      "title": "Витамин А",
      "image": "Vitamin1",
      "favorite": false
    },
    {
      "title": "Витамин B6",
      "image": "Vitamin2",
      "favorite": false
    }
  ]
}

我可以读取文件:

struct ResponseData: Decodable {
    var person: [Person]
}

struct Person : Decodable {
    var title: String
    var image: String
    var favorite: Bool
}

从文件函数加载json:

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
}

var VTarray2 = [Person]()

override func viewDidLoad() {
    super.viewDidLoad()

    VTarray2 = loadJson(filename: "document")!
    VTarray2[0].favorite = true
}

我编写函数并得到我的编辑 json! 现在我需要在文件中写json

func encoderJsonFiles() { 
    let encoder = JSONEncoder()
    do {
        let jsonData = try encoder.encode(VTarray2)
        if let jsonString = String(data: jsonData, encoding: .utf8) {
           print(jsonString)
        }
    } catch {
            print(error.localizedDescription)
    }
 }

我写了保存到文件的函数

func SaveToFile(){
 let file = "Myfile.json" 

            if let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {

                let fileURL = dir.appendingPathComponent(file)

                do {
                    let jsonData = try encoder.encode(VTarray2)
                    try jsonData.write(to: fileURL)
                }
                catch {/* error handling here */}
}

添加函数 LoadFromJsonFile() 我读数据。但我无法以 JSON 格式解码它们 如何解析数据?

func LoadFromJsonFile() {
    let fileURL = UserDefaults.standard.url(forKey: "fileURL")!
    do {
        let myJSON = try String(contentsOf: fileURL, encoding: .utf8)
        print("JSONLoad : \(myJSON)")
        print("JSONPath: \(fileURL)")
    }
    catch {print("Error")}
}

谢谢!

【问题讨论】:

标签: json swift swift4


【解决方案1】:

使用

struct ResponseData: Codable {

能够解码

let dic = try decoder.decode(ResponseData.self, from: data)

并编码

let data = try JSONEncoder().encode(item)

【讨论】:

  • let data = try JSONEncoder().encode(VTarray2) 如何将结果写入json文件?
  • 你不能保存在主包中,你需要创建一个txt文件说文档目录并保存数据
  • 我快完成了!我不知道如何从我的文件 JSON 中读取结构
猜你喜欢
  • 1970-01-01
  • 2020-11-10
  • 2019-01-19
  • 1970-01-01
  • 2021-04-30
  • 2022-08-13
  • 2018-10-25
  • 1970-01-01
  • 2018-03-27
相关资源
最近更新 更多