在Swift 5中为字典创建扩展名[String:Any]

时间:2019-06-12 10:02:42

标签: ios swift

我想为从API响应接收到的字典[String:Any]创建扩展名。

现在我正在按照以下方式进行操作

我已经创建了func getDataFromJson,它可以正常工作,请让我知道该怎么做。

func getDataFromJson(json: AnyObject) -> Data?{
    do {
        print("json = \(json)")
        return try JSONSerialization.data(withJSONObject: json, options: JSONSerialization.WritingOptions.prettyPrinted)
    } catch let myJSONError {
        print("\n\n\nError => getDataFromJson => \(myJSONError)")
    }
    return nil;
}

这是我的回复,我想“数据”到数据

{
    "status": true,
    "message": "Country List",
    "data": [
        {
            "id": 1,
            "name": “ABC”,
            "code": "A",
            "phone_code": "+91”,
            "flag": "country-flags/-shiny.png"
        },
        {
            "id": 2,
            "name": “ZYX”,
            "code": “Z”,
            "phone_code": "+1”,
            "flag": "country-flags/-shiny.png"
        }
     ]
}
  

我想以这种方式jsonResponse["data"].retriveData()

获取数据

4 个答案:

答案 0 :(得分:1)

这是对字典进行编码的简单函数,该函数会引发任何错误,因此可以正确处理。由于JSONSerialization.data(withJSONObject:采用了Any参数,因此也可以为数组等实现此功能

extension Dictionary {
    func retriveData() throws -> Data {
        return try JSONSerialization.data(withJSONObject: self)
    }
}

简单的例子

let dict = ["abc": 123, "def": 456]

do {
   let data = try dict.retriveData()
   let result = try JSONDecoder().decode([String:Int].self, from:data)
   print(result)
} catch {
    print(error)
}

如果您使用的是Swift 5,则另一种方法是使用Result(在vadian发表评论后简称)

extension Dictionary {
    func retriveData() -> Result<Data, Error> {
        return Result { try JSONSerialization.data(withJSONObject: self) }            
    }
}

和示例

let result = try dict.retriveData()
switch result {
   case .success(let data):
       let dictionary = try JSONDecoder().decode([String:Int].self, from:data)
       print(dictionary)
   case .failure(let error):
      print(error) 
}

答案 1 :(得分:0)

可以将功能副本复制到扩展名

extension Dictionary {
        func retriveData() -> Data? {
            do {
                return try JSONSerialization.data(withJSONObject: self, options: .prettyPrinted)
            } catch let myJSONError {
                print("\n\n\nError => getDataFromJson => \(myJSONError)")
            }
            return nil
        }
 }

答案 2 :(得分:0)

更正json

{
    "status": true,
    "message": "Country List",
    "data": [
        {
        "id": 1,
        "name": "ABC",
        "code": "A",
        "phone_code": "+91",
        "flag": "country-flags/-shiny.png"
        },
        {
        "id": 2,
        "name": "ZYX",
        "code": "Z",
        "phone_code": "+1",
        "flag": "country-flags/-shiny.png"
        }
    ]
}

型号

struct Datum: Codable {
    let id: Int
    let name, code, phoneCode, flag: String 
}

仅解码数据

        let str = """
{
    "status": true,
    "message": "Country List",
    "data": [{
            "id": 1,
            "name": "ABC",
            "code": "A",
            "phone_code": "+91",
            "flag": "country-flags/-shiny.png"
        },
        {
            "id": 2,
            "name": "ZYX",
            "code": "Z",
            "phone_code": "+1",
            "flag": "country-flags/-shiny.png"
        }
    ]
}

"""

    do {

        let dic = try JSONSerialization.jsonObject(with: Data(str.utf8)) as! [String:Any]
        let content = try JSONSerialization.data(withJSONObject: dic["data"])
        let dec = JSONDecoder()
        dec.keyDecodingStrategy = .convertFromSnakeCase
        let res = try dec.decode([Datum].self, from: content)
        print(res)
    }
    catch {

        print(error)
    }

答案 3 :(得分:0)

请尝试此操作

// Response Dictionary
let jsonResponse : [String:Any] = ["data":["key1":"value1",
                                           "key2":"value2",
                                           "key3":"value3",
                                           "key4":"value4"]]

// check dictionary contains value for key "data"
if let dataDict = jsonResponse["data"] as? [String:Any] {
    // convert dictionary to data
    let jsonData = dataDict.retriveData()
    print("Json Data :- ", jsonData != nil ? "Success" : "Data is nil")
}

// Dictionary exxtension for converting dictionary to json data
extension Dictionary {
    func retriveData() -> Data? {
        do {
            print("json = \(self)")
            return try JSONSerialization.data(withJSONObject: self, options: JSONSerialization.WritingOptions.prettyPrinted)
        } catch let myJSONError {
            print("\n\n\nError => getDataFromJson => \(myJSONError)")
        }
        return nil;
    }
}