如何从json中基于数组内的特定值获取结果?斯威夫特4.2

时间:2019-05-26 14:27:39

标签: arrays json swift alamofire decodable

我是新手,可能我的问题很简单,但我不知道如何解决。我如何获取值取决于json嵌套数组中的特定属性值?在这种情况下,我想过滤属性公司并将结果存储在newFirm中,仅在子节点名称A =“ Clothes”的位置。这是我的JSON和代码。

[
    {
        "id": 156,
        "active": "A",
        "logo": 282,
        "name": "AfrM C",
        "description": "some text",
        "nameShort": "AFR",
        "activities": [
            {
                "id": 6,
                "nameA": "Clothes",
                "picture": 197,
                "activity": {
                    "id": 2,
                    "nameB": "Goods",
                    "pic": 1
                },
                "priority": 2
            }
        ]
    },
    {
        "id": 177,
        "active": "A",
        "logo": 303,
        "name": "Aqu Plus",
        "description": "some text2",
        "nameShort": "AQU",
        "activities": [
            {
                "id": 7,
                "nameA": "Shoes",
                "picture": 165,
                "activity": {
                    "id": 1,
                    "nameB": "Favor",
                    "pic": 2
                },
                "priority": 1
            }
        ]
    }
...
]
import Foundation

struct Firm : Decodable {
    let id : Int?
    let active: String?
    let logo : Int?
    let name : String?
    let description : String?
    let nameShort : String?
    let activities : [Activities?]

    enum CodingKeys: String, CodingKey {
        case id, active, logo, name, description, nameShort, activities
    }
}

struct Activities : Decodable {
    let id : Int?
    let nameA : String?
    let picture : Int?
    let activity : Activity?
    let priority : Int?

    enum CodingKeys : String, CodingKey {
        case id, nameA, picture, activity, priority
    }
}

struct Activity : Decodable {
    let id : Int?
    let nameB : String?
    let pic : Int?

    enum CodingKeys : String, CodingKey {
        case id, nameB, pic
    }
}
import UIKit
import Alamofire

class ViewController: UIViewController {

    let firmUrl = "http://xxx.xxx.xxx/"
    var firm : [Firm] = []
    var newFirm : [Firm] = []
    var specificValue = "Shoes"

    override func viewDidLoad() {
        super.viewDidLoad()
        getApi()
    }

    func getApi(){
        Alamofire.request(firmaUrl, method: .get).responseJSON {(response) in
            if response.result.isSuccess {
                guard let responseData = response.data else {return}
                self.firm = try! JSONDecoder().decode([Firm].self, from: responseData)
                //here i want somehow to filter somehow self.firm
                //where nameA property is "Clothes"
                //and store in newFirm
                }
            }
            else {
                 print("Error: \(String(describing: response.result.error))")
            }
        }
    }
}

0 个答案:

没有答案