读/写本地json文件swift 4 [英] read/write local json file swift 4
本文介绍了读/写本地json文件swift 4的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
请帮助我! 我在项目中添加了一个json文件 我的json文件:
Please help me! I added a json file to the project My json file:
{
"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:
Load json from file fonction:
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
I write function and I get my edit json! Now I need to write json in the file
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)
}
}
我编写了保存到文件的功能
I write function for save to file
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格式对其进行解码 如何解析数据?
Add function LoadFromJsonFile() I read data. but I can't decode them in JSON format How do I parse data?
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")}
}
谢谢!
推荐答案
使用
struct ResponseData: Codable {
能够解码
let dic = try decoder.decode(ResponseData.self, from: data)
并编码
let data = try JSONEncoder().encode(item)
这篇关于读/写本地json文件swift 4的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文