gpt4 book ai didi

ios - swift ,Alamofire,SwiftyJSON : How to parsing arrayObject

转载 作者:行者123 更新时间:2023-11-28 10:54:51 26 4
gpt4 key购买 nike

我不知道如何使用 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"
}
]
}
]
}
}

模型.swift

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 文件解析为类别和子类别的数组

声明类别数组

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)

创建类别并将它们附加到数组

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)!)
}
}
}

关于ios - swift ,Alamofire,SwiftyJSON : How to parsing arrayObject,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44296153/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com