请帮助我! 我在项目中添加了一个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")}
}
谢谢!
答案 0 :(得分:2)
使用
struct ResponseData: Codable {
能够解码
let dic = try decoder.decode(ResponseData.self, from: data)
并编码
let data = try JSONEncoder().encode(item)