如何将 [[String:AnyObject]] 从字符串映射到类



我正在尝试从字符串中添加对象数组。我正在从 API 调用中获取加密字符串。解密数据后,获取一串JSON结构,如下所示:

{
     "request_id”:”abcds123”,
     "status”:”18”,
     "message":"SUCCESS",
     "customer_name”:”XXXX X XX”,
     "mobile_no”:”123456789”,
     "email_id":"xxx@xxx.com",
     “function”:
                [
                 {“funcCode”:”OPN”,,”funcVal”:0,”funcType":"M"},
                 {“funcCode”:”CLO”,”funcVal”:1,”funcType":"M"}
                ],
     “dataID”:”ASD1234”,
     ”valid”:”Y”
}

这是通用的 API 响应,将非常基于响应。我可以将"函数"元素映射到[[字符串:任何对象]]。但无法将其直接映射到类。我们是否有更简单的方法可以在 swift 中将"函数"数组提取到类中,而无需迭代数据并添加到数组变量中:

var mainObject : [String:Any] = [:]
if let data = result.data(using: .utf8) {
  do {
    mainObject =  (try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any])!
    if let status = mainObject[“status”] as? String {
      switch(status) {
      case 200:
        if mainObject.keys.contains(“customer_name”) {
          //do something
        }
        if mainObject.keys.contains(“function”) {
          if let functionList = mainObject[“function”] as? [[String:AnyObject]] {
            //map functionList to class [Function]
            for function in functionList {
              print(“Function ====> ", function)
              //create a class and add to an array of Function class
            }
          }
        }
      }
    } catch {
      print(error.localizedDescription)
    }
  }
}

来自响应的结果字符串。

目标是单独提取"函数"数据并将其映射到类,而无需创建容器类/结构。

您可以使用

Codable 协议来帮助您将 JSON 数据映射到对象中。

首先创建结构:

struct MyFunction: Codable {
    let funcCode: String
    let funcVal: Int
    let funcType: String
}
struct MyContainer: Codable {
     let status: string,
     let message: string,
     // Another properties
     let function: [MyFunction]
}

然后,您只需使用解码函数将 JSON 字符串映射到对象:

if let jsonData = result.data(using: .utf8) {
  do {
    let decoder = JSONDecoder()
    let mainObject = try decoder.decode(MyContainer.self, for: jsonData)
  } catch {
    print(error.localizedDescription)
  }
}

有关更多信息,您可以查看此博客文章。

最先进的是(De)Codable协议,您可以将JSON字典直接解码为结构体

struct Main: Decodable {
    let status, customerName: String
    let function : [Function]
}
struct Function: Codable {
    let funcCode, funcType: String
    let funcVal : Int
}

let data = Data(result.utf8)
do {
    let decoder = JSONDecoder()
    decoder.keyDecodingStrategy = .convertFromSnakeCase
    let mainObject = try decoder.decode(Main.self, from: data)
    print(mainObject.customerName)
    print(mainObject.function)
} catch {
  print(error)
}

注意:JSON 字典永远不会在 Swift 3+ 中[String:AnyObject],它是[String:Any]


编辑:如果只想Function结构保留JSONSerialization代码,请省略Main结构,将mainObject声明为

var functions = [Function]()

并映射 JSON 数组

if let functionList = mainObject["function"] as? [[String:Any]] {
   functions = functionList.map {Function(funcCode: $0["funcCode"] as! String,
                                           funcVal: $0["funcVal"] as! Int,
                                           funcType: $0["funcType"] as! String) }    
}

要将数组写入用户默认值,请使用 JSONEncoderData 对其进行编码。

最新更新