[英]Parsing Alamofire result into objects in Swift (using: Alamofire, SwiftyJSON & ObjectMapper)
[英]swift, Alamofire, SwiftyJSON : How to parsing arrayObject
我不知道如何使用SwiftyJSON.JSON制作数组,我可以使用SwiftyJSON.JSON解析结构,但是无法解析对象数组。 请帮我。
JSON格式
{
"result": {
"list": [
{
"categoryId": 1,
"categoryNm": "main_1",
"subCategoryList": [
{
"categoryId": 2,
"categoryNm": "sub_1_1"
},
{
"categoryId": 4,
"categoryNm": "sub_1_2"
},
{
"categoryId": 5,
"categoryNm": "sub_1_3"
},
{
"categoryId": 6,
"categoryNm": "sub_1_4"
},
{
"categoryId": 28,
"categoryNm": "sub_1_5"
}
]
},
{
"categoryId": 7,
"categoryNm": "main_2",
"subCategoryList": [
{
"categoryId": 9,
"categoryNm": "sub_2_1"
},
{
"categoryId": 10,
"categoryNm": "sub_2_2"
},
{
"categoryId": 11,
"categoryNm": "sub_2_3"
}
]
}
]
}
}
模型模型
struct Model {
public let list: Array<Category>
public init?(json: JSON) {
self.list = json["list"].arrayObject as! Array<Category>
}
}
struct Category {
public let categoryId: NSInteger
public let categoryNm: NSString
public let subCategoryList: Array<SubCategory>
public init?(json: JSON) {
self.categoryId = json["categoryId"].intValue as NSInteger
self.categoryNm = json["categoryNm"].stringValue as NSString
self.subCategoryList = json["subCategoryList"].arrayObject as! Array<SubCategory>
}
}
struct SubCategory {
public let categoryId: NSInteger
public let categoryNm: NSString
public init?(json: JSON) {
self.categoryId = json["categoryId"].intValue as NSInteger
self.categoryNm = json["categoryNm"].stringValue as NSString
}
}
ViewController.swift
override func viewDidLoad() {
super.viewDidLoad()
...
switch response.result {
case .success(let value):
let json = JSON(value)
let resultModel = Model.init(json: json["result"])
case .failure(let error):
print(error)
}
我不知道如何使用SwiftyJSON.JSON制作数组,我可以使用SwiftyJSON.JSON解析结构,但是无法解析对象数组。 请帮我。
以下代码将my.json文件解析为Categories和SubCategories数组
声明categories
数组
var categories = [Category]()
打开文件并创建一个JSON
对象
let path = Bundle.main.path(forResource: "my", ofType: "json")!
let jsonData = NSData.init(contentsOfFile: path)
let json = JSON(data: jsonData! as Data)
创建categories
并将其附加到数组
for categoryArray in json["result"]["list"].array! {
guard let category = Category(json: categoryArray) else { continue }
categories.append(category)
}
print(categories)
声明Category
结构如下
struct Category {
public let categoryId: NSInteger
public var subCategories = [SubCategory]()
public init?(json: JSON) {
self.categoryId = json["categoryId"].intValue as NSInteger
self.categoryNm = json["categoryNm"].stringValue as NSString
for subCategory in json["subCategoryList"].array! {
subCategories.append(SubCategory(json: subCategory)!)
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.