获取JSON键字典的值

时间:2018-10-13 01:19:37

标签: json swift swifty-json

我正在尝试使用Alamofire和SwiftyJSON从API获取密钥[“ sub_depart”]中的密钥值[“ sub_department_name”]。

那是API响应:

[
    {
        "main_department_id": "1",
        "main_department_name": "mar",
        "main_department_image": "8.jpg",
        "sub_depart": [
            {
                "sub_department_id": "4",
                "sub_department_name": "add\r\n",
                "sub_department_image": "16.png"
            },
            {
                "sub_department_id": "5",
                "sub_department_name": "rol",
                "sub_department_image": "10.jpg"
            }
        ]
    },
    {
        "main_department_id": "2",
        "main_department_name": "fam ",
        "main_department_image": "14.jpg",
        "sub_depart": [
            {
                "sub_department_id": "6",
                "sub_department_name": "fam wor",
                "sub_department_image": "23.jpg"
            }
        ]
    },
    {
        "main_department_id": "3",
        "main_department_name": "sau",
        "main_department_image": "6.jpg",
        "sub_depart": [
            {
                "sub_department_id": "7",
                "sub_department_name": "sau",
                "sub_department_image": "26.jpg"
            },
            {
                "sub_department_id": "8",
                "sub_department_name": "goo",
                "sub_department_image": "31.jpg"
            }
        ]
    },
    {
        "main_department_id": "9",
        "main_department_name": "try",
        "main_department_image": "6.jpg",
        "sub_depart": []
    }
]

这就是我使用的模型:

class CategoriesDep: NSObject {
    var depName: String
    var depImage: String
    var subName: String

    init?(dict: [String: JSON]) {
       guard let image = dict["main_department_image"]?.imagePath, !image.isEmpty else { return nil }

        self.depImage = image
        self.depName = (dict["main_department_name"]?.string)!
        self.subName = (dict["sub_department_name"]?.string)!
    }

这就是获取请求:

class func categoryDep (completion: @escaping(_ error: Error?, _ data: [CategoriesDep]?) -> Void) {
    Alamofire.request(URLs.categoryDep).responseJSON { (response) in
        switch response.result {
        case.failure(let error):
            completion(error,nil)
            print(error)
        case .success(let value):
            let jsonData = JSON(value)
               //print(jsonData)
            guard let dataArray = jsonData.array else{
                completion(nil , nil)
                return
            }
            var main = [CategoriesDep]()
            for data in dataArray {
                if let data = data.dictionary , let result = CategoriesDep.init(dict: data) {
                    main.append(result)
                    print("good")
                }
            }

            completion(nil, main)
        }
    }
}

2 个答案:

答案 0 :(得分:0)

看起来sub_depart是一个对象数组,因此您需要通过索引来访问它,例如['sub_depart'] [0] ['sub_department_name']。

答案 1 :(得分:0)

您可以使用Codable

let res = try? JSONDecodable().decode(Root.self,from:jsonData) 
let needed = res.subDepart.map{ $0.subDepartmentName }

struct Root: Codable {
    let mainDepartmentID, mainDepartmentName, mainDepartmentImage: String
    let subDepart: [InnerItem]

    enum CodingKeys: String, CodingKey {
        case mainDepartmentID = "main_department_id"
        case mainDepartmentName = "main_department_name"
        case mainDepartmentImage = "main_department_image"
        case subDepart = "sub_depart"
    }
}

struct InnerItem: Codable {
    let subDepartmentID, subDepartmentName, subDepartmentImage: String

    enum CodingKeys: String, CodingKey {
        case subDepartmentID = "sub_department_id"
        case subDepartmentName = "sub_department_name"
        case subDepartmentImage = "sub_department_image"
    }
}

init?(dict: [String: JSON]) {  
  self.depImage = dict["main_department_image"]?.string ?? ""
  self.depName = dict["main_department_name"]?.string  ?? ""
  let arr = dict["sub_department_name"]?.arrayValue
  let dic = arr?[0].dictionary
  self.subName = dic?["sub_department_name"] ?? ""
}