如何在iOS Swift 3中将JSON-String转换为字典数组

时间:2016-12-15 11:27:07

标签: ios json swift

我有这个字符串

[{\"label\":\"Issue Name\",\"value\":\"my dirst iOS \",\"_id\":\"issueName\"},{\"label\":\"Issue DueDate\",\"value\":\"15-12-2016\",\"_id\":\"dueDate\"}]

我想将其转换为[NSDictionary]类型,例如

[
  {
    "label": "Issue Name",
    "value": "my dirst iOS ",
    "_id": "issueName"
  },
  {
    "label": "Issue DueDate",
    "value": "15-12-2016",
    "_id": "dueDate"
  }
]

有人可以告诉我该怎么做。我已经尝试过How to convert a JSON string to a dictionary?

2 个答案:

答案 0 :(得分:3)

首先尝试删除斜杠

stringJson.stringByReplacingOccurrencesOfString("\\", withString: "")

然后用JsonConverter转换它

func convertToDictionary(text: String) -> Any? {

     if let data = text.data(using: .utf8) {
         do {
             return try JSONSerialization.jsonObject(with: data, options: []) as? Any
         } catch {
             print(error.localizedDescription)
         }
     }

     return nil

}

然后

    if let list = self.convertToDictionary(text: stringJson) as? [AnyObject] {

       print(list);
    }

答案 1 :(得分:1)

Swift 5 简单方法

//MARK:- Calling
if let list = self.convertToDictionary(text: stringJson) as? [AnyObject] {

   print(list);
}


//MARK:- Remove the Slashes
let text = stringJson.replacingOccurrences(of: "\\", with: "")

//MARK:- Convert it with JsonConverter
func convertToDictionary(text: String) -> Any? {

 if let data = text.data(using: .utf8) {
     do {
         return try JSONSerialization.jsonObject(with: data, options: []) as? Any
     } catch {
         print(error.localizedDescription)
     }
 }

 return nil

}