我正在编写一个需要读取JSON文件的IOS应用程序。 我知道最好的方法是为该json文件编写一个结构,然后将json解析为该结构以便可以自由使用。
我有一个Json文件,该文件本地保存在其中一个文件夹中
{
"colors": [
{
"color": "black",
"category": "hue",
"type": "primary",
"code": {
"rgba": [255,255,255,1],
"hex": "#000"
}
},
{
"color": "white",
"category": "value",
"code": {
"rgba": [0,0,0,1],
"hex": "#FFF"
}
},
{
"color": "red",
"category": "hue",
"type": "primary",
"code": {
"rgba": [255,0,0,1],
"hex": "#FF0"
}
},
{
"color": "blue",
"category": "hue",
"type": "primary",
"code": {
"rgba": [0,0,255,1],
"hex": "#00F"
}
},
{
"color": "yellow",
"category": "hue",
"type": "primary",
"code": {
"rgba": [255,255,0,1],
"hex": "#FF0"
}
},
{
"color": "green",
"category": "hue",
"type": "secondary",
"code": {
"rgba": [0,255,0,1],
"hex": "#0F0"
}
},
],
"people": [
{
"first_name": "john",
"is_valid": true,
"friends_list": {
"friend_names": ["black", "hub", "good"],
"age": 13
}
},
{
"first_name": "michal",
"is_valid": true,
"friends_list": {
"friend_names": ["jessy", "lyn", "good"],
"age": 19
}
},
{
"first_name": "sandy",
"is_valid": false,
"friends_list": {
"friend_names": ["brown", "hub", "good"],
"age": 15
}
},
]
}
我为两个表中的每个表创建了一个结构:
import Foundation
struct Color {
var color: String
var category: String
var type: String
var code: [JsonCodeStruct]
}
struct Poeople {
var firsName: String
var is_valid: Bool
var friendsNames: [JsonFriendNames]
}
struct JsonFriendNames {
var friendNames: [String]
var age: String
}
struct JsonCodeStruct {
var rgba: [Double]
var hex: String
}
,我想打开本地json文件 并为其分配我给出的结构,然后在代码中轻松阅读它们。
您能建议我一种方法吗?
答案 0 :(得分:4)
首先,您需要一个伞形结构来解码colors
和people
键
struct Root: Decodable {
let colors: [Color]
let people : [Person]
}
结构中的类型部分错误。与Color
相关的结构是
struct Color: Decodable {
let color: String
let category: String
let type: String?
let code : ColorCode
}
struct ColorCode: Decodable {
let rgba : [UInt8]
let hex : String
}
和Person
相关的结构是
struct Person: Decodable {
let firstName : String
let isValid : Bool
let friendsList : Friends
}
struct Friends: Decodable {
let friendNames : [String]
let age : Int
}
假设您使用
读取文件let data = try Data(contentsOf: URL(fileURLWithPath:"/...."))
您可以使用
将JSON解码为给定的结构let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
do {
let result = try decoder.decode(Root.self, from: data)
print(result)
} catch { print(error) }