如何在Swift3中将String转换为NSArray

时间:2018-10-24 05:57:41

标签: ios json swift3

以下一行是我的String

"(\n {\n ID = 338;\n Name = "Driver ";\n },\n {\n ID = 339;\n Name = "Officer ";\n }\n)"

我需要NSArray数据的以下类型

[
 {
    "ID": 338,
    "Name": "Driver"
 },
 {
    "ID": 339,
    "Name": "Officer"
 }
]

以下是我到目前为止所做的代码

func fillupDataIntoArray(_ result: NSArray,IsFrom:String) {

    let resultArray : NSArray = result as NSArray;

     if IsFrom == "tbl_AttendanceLocation" {
     let dic = NSMutableArray()
     for i:Int in 0 ..< resultArray.count {
     let tempDict = resultArray[i] as! NSDictionary

        dic.add(tempDict as NSDictionary)
     }
        taskList_Array = []
        taskList_Array = dic.mutableCopy() as! NSMutableArray
     }
}

请帮助我!

1 个答案:

答案 0 :(得分:0)

尝试这种方式:

struct Product: Codable {
    var ID: String
    var Name: String
}

let json = """
{
    "ID": "iuweguewbgw",
    "Name": "Sara",
}
""".data(using: .utf8)!

let decoder = JSONDecoder()
let product = try decoder.decode(GroceryProduct.self, from: json)

您还可以尝试使用正则表达式。