从JSON响应中获取一些值

我需要使用Alamofire解码作为JSON响应收到的NSDictionary。

这是我如何获得JSON响应:

//to get JSON return value

                        if let result = response.result.value {
                            let JSON = result

                            print("Result:",JSON)



                        }

这是响应的打印输出:

Result: {
    error = 0;
    id = "<null>";
    precio =     {
        p1 = 280;
        p10 = 60;
        p11 = 70;
        p12 = 70;
        p13 = 60;
        p14 = 75;
        p15 = 35;
        p16 = 35;
        p17 = 80;
        p18 = 75;
        p19 = 80;
        p2 = 230;
        p20 = 70;
        p21 = 55;
        p22 = 0;
        p23 = 65;
        p3 = 180;
        p4 = 150;
        p5 = 100;
        p6 = 75;
        p7 = 65;
        p8 = 65;
        p9 = 60;
    };
}

我需要获取一些值,例如p12和p15。

如果有帮助,我创建了一个名为PreciosTicket的类:

struct PreciosTicket:Decodable {


    let p1: String
    let p2: String
    let p3: String
    let p4: String
    let p5: String
    let p6: String
    let p7: String
    let p8: String
    let p9: String
    let p10: String
    let p11: String
    let p12: String
    let p13: String
    let p14: String
    let p15: String
    let p16: String
    let p17: String
    let p18: String
    let p19: String
    let p20: String
    let p21: String
    let p22: String
    let p23: String

}
评论
  • ut_et
    ut_et 回复

    向下转换到字典:

    if let result = response.result.value as? [String: AnyObject],
        let precio = result["precio"] as? [String: AnyObject] {
        print(precio["p12"], precio["p15"])
    }
    

    Using Codable is a much better method.