简单数据处理
定义模型名称
struct GroceryProduct: Codable {
var name: String
var points: Int
var description: String?
}
json数据定义
let json = """
{
"name": "Durian",
"points": 600,
"description": "A fruit with a distinctive scent."
}
""".data(using: .utf8)!
数据解析
// 对data数据进行解析
let decoder = JSONDecoder()
let product = try? decoder.decode(GroceryProduct.self, from: json)
// 读取model中数据
print(product?.description ?? "nil")
复杂数据处理
定义json
let json2 = """
{
"id": 1001,
"name": "Durian",
"points": 600,
"parameters": {
"size": "80*80",
"area": "Thailand",
"quality": "bad"
},
"description": "A fruit with a distinctive scent."
}
""".data(using: .utf8)!
定义模型
struct GroceryProduct: Codable {
var ID: Int
var name: String
var points: Int?
var description: String?
var parameters: Parameters?
enum CodingKeys: String, CodingKey {
case ID = "id"
case name
case points
case description
case parameters
}
struct Parameters: Codable {
var size: String?
var area: String?
var quality: Quality?
}
enum Quality: String, Codable {
case good, caporal, bad
}
}
解析数据处理
do {
decoder.keyDecodingStrategy = .convertFromSnakeCase
let product2 = try decoder.decode(GroceryProduct.self, from: json2)
print(product2.parameters?.quality ?? "unknown")
} catch let error {
print(error)
}
列表数据处理
{
"code": 10000,
"msg": "请求成功",
"datas" : [
{
"id": 1001,
"name": "Durian",
"points": 600,
"parameters": {
"size": "80*80",
"area": "Thailand",
"quality": "bad"
},
"description": "A fruit with a distinctive scent."
},
{
"id": 1002,
"name": "Apple",
"points": 600,
"parameters": {
"size": "80*80",
"area": "China",
"quality": "good"
},
"description": "A round fruit with shiny red or green skin and firm white flesh."
},
{
"id": 1003,
"name": "Arange",
"points": 600,
"parameters": {
"size": "80*80",
"area": "China",
"quality": "caporal"
},
"description": "A round citrus fruit with thick reddish-yellow skin and a lot of sweet juice."
},
{
"id": 1004,
"name": "Banana",
"points": 600,
"parameters": {
"size": "80*80",
"area": "Malaysia",
"quality": "good"
},
"description": "A long curved fruit with a thick yellow skin and soft flesh, that grows on trees in hot countries."
}
]
}
创建数据模型
struct ProductListModel: Codable {
var code: Int
var msg: String
var datas: [GroceryProduct]
}
请求数据源并解析
guard let urlPath = Bundle.main.path(forResource: "ProductList", ofType: "json") else { return }
do {
let data = try Data(contentsOf: URL(fileURLWithPath: urlPath))
let jsonData: Any = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers)
print("present = ", jsonData)
let product3 = try decoder.decode(ProductListModel.self, from: data)
print(product3.datas[2].ID)
} catch let error {
print(error)
}
注意事项
- 数据类型匹配,要不就会出现解析失败
网友评论