简体   繁体   中英

Swift: How to work with JSON when you don't know the name of the keys or the data type of the values

I am having trouble wrapping my head around how to work with JSON where I will not know the name of the keys, or the data type of the values. Each time I get the data, the JSON will have different keys, and different data types. I have been trying to use generics to perform this action, but am not having much success.

I apologize, if others have already asked this question. I searched, but could not find a good explanation of how to achieve working with dynamic JSON in an SDK.

edited I had some code in my question that was not making much sense, I have removed it since it will probably not help others.

If you can't know the value types, how many values or the name of the properties the json contains why don't you just parse the json string into a dictionary and then iterate through the keys of this dictionary and look for what you want. Something like this :

if let dict = "Your json response".toDictionary(){
            for (key, value) in dict.enumerated(){
                //Do something with key || value
            }
        }

extension String {
    func toDictionary() -> [String: Any]? {
        return try? JSONSerialization.jsonObject(with: data(using: .utf8)! , options: []) as? [String: Any]
    }
}

使用Charles Web Debugging Proxy捕获您作为请求发送的内容以及您作为响应收到的内容,并且不要忘记按Shift + Command + P在其上启用 macOs 代理。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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