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

时间:2019-01-21 09:08:34

标签: ios json swift

我正在尝试从字符串中添加对象数组。我从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响应,将非常基于响应。 我可以将“功能”元素映射到[[String:AnyObject]]。但是无法将其直接映射到类。我们是否有一种更简单的方法来快速将“函数”数组提取到类中而不迭代数据并添加到数组变量中?

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)
    }
  }
}

结果字符串来自响应。

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

2 个答案:

答案 0 :(得分:2)

您可以使用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)
  }
}

有关更多信息,您可以查看此blog post

答案 1 :(得分:0)

最先进的是(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)
}

注意:在Swift 3+中,JSON字典永远不会[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) }    
}

要将数组写入UserDefaults,请使用JSONEncoderData对其进行编码。