简体   繁体   English

如何使用Coadable从字典中解码.keys

[英]How to decode .keys from dictionary using Coadable

I have a below JSON response. 我有下面的JSON响应。 And I want to fetch the allkeys of “data” which is [“rules”, “preference”, “goals”] using .keys method. 我想使用.keys方法获取“数据”的所有关键字,即“规则”,“首选项”,“目标”]。 But I couldn't get the array of allkeys using .keys feature. 但是我无法使用.keys功能获得allkey数组。 I have attached my code snippet also. 我也附上了我的代码段。 if you had faced this one, please suggest me to rid of this concern. 如果您曾经遇到过这种情况,请建议我摆脱这种担忧。

Although, I can get these allKeys using ObjectMapper and native Dictionary objects. 虽然,我可以使用ObjectMapper和本机Dictionary对象获得这些allKeys。 I just need to know why I couldn't achieve this using Codable. 我只需要知道为什么我无法使用Codable做到这一点。

My json response 我的json回应

{
    "statusCode": 200,
    "status": "success",
    "message": null,
    "data": {
        "rules": {
            "goals": {
                "min": "1",
                "max": "3"
            }
        },
        "preference": [
            1,
            2,
            3
        ],
        "goals": {
            "total": 4,

            "data": []
        }
    }
}

My code Snippet: 我的代码段:

struct MeetingsDataModal: Codable {
    let statusCode: Int?
    let status: String?
    let message: String?
    let data: Results?
    enum CodingKeys: String, CodingKey {
        case statusCode = "statusCode"
        case status = "status"
        case message = "message"
        case data = "data"
    }
    func allkeys() {

    }
}

struct Results : Codable {
    let rules: Rules?
    let preference: [Preference]?
    let goals: Goals?
    enum CodingKeys: String, CodingKey {
        case rules = "rules"
        case preference = "preference"
        case goals = "goals"
    }
}

struct Rules : Codable {
}
struct Preference : Codable {
}
struct Goals : Codable {
}

My expectation 我的期望

let content = try JSONDecoder().decode(MeetingsDataModal.self, from: (response as? Data)!)
print(content.data.keys)

But I am getting, 但我明白了

Value of type 'Results?' 类型“结果?”的值 has no member 'keys' 没有成员“键”

Perhaps I am not understanding the question well but your "keys" are defined by your Codable protocol - so they are known. 也许我不太清楚这个问题,但是您的“键”是由您的Codable协议定义的-因此它们是已知的。 If you are using Swift 4.2+ you can take advantage of the CaseIterable protocol 如果您使用的是Swift 4.2+,则可以利用CaseIterable协议

struct Results: Codable {
    let testOne: Int
    let testTwo: String
    enum CodingKeys: String, CodingKey, CaseIterable {
        case testOne
        case testTwo
    }
}

Results.CodingKeys.allCases.map { $0.rawValue }

If you do need .keys. 如果您确实需要.keys。 could add two-line code : 可以添加两行代码:

   struct Results : Codable {
        let rules: Rules?
        let preference: [Preference]?
        let goals: Goals?
        enum CodingKeys: String, CodingKey {
            case rules = "rules"
            case preference = "preference"
            case goals = "goals"
        }

        var keys : [String]{
            return["rules", "preference","goals"]
        }
    }

Actually, if you don't like encoding/decoding way , we have another traditional JSON object can help you to handle unstructured JSON. 实际上,如果您不喜欢编码/解码方式,我们还有另一个传统的JSON对象可以帮助您处理非结构化JSON。

    let obj =   try JSONSerialization.jsonObject(with: response!, options: JSONSerialization.ReadingOptions.allowFragments)

    print((((obj as! [String: Any?])["data"]) as! [String: Any?]).keys)

Here is one way to decode you data structure. 这是一种解码数据结构的方法。

           let d = """
        {
            "statusCode": 200,
            "status": "success",
            "message": null,
            "data": {
                "rules": {
                    "goals": {
                        "min": "1",
                        "max": "3"
                    }
                },
                "preference": [
                1,
                2,
                3
                ],
                "goals": {
                    "total": 4,

                    "data": []
                }
            }
        }
        """.data(using: .utf8)!


        struct MeetingsDataModal: Decodable {
            let statusCode: Int
            let status: String
            let message: String?
            let data: Results
        }

        struct Results : Decodable {
            let rules: Rules
            let preference: [Int]
            let goals: Goals
        }

        struct Rules : Decodable {
            let goals : DirectData
        }
        struct DirectData : Decodable{
            let min : String
            let max : String
        }
        struct Goals : Decodable {
            let total : Int
            let data : [String]
        }

        let data0 = try JSONDecoder().decode(MeetingsDataModal.self, from: d)
        print(data0)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM