我尝试将Json字符串(响应)转换为json对象,但是在JSONSerialization之后,输出不清楚

时间:2018-11-05 09:22:08

标签: ios json swift4.2

我得到了Web服务的响应,并尝试对其进行处理以将其放入模型中,但是我无法使用它。

这是 response.string

"{\"USER_NO\":1,\"USER_NAME\":\"المسار البديل لتكنولوجيا المعلومات\",\"TASK_CATEGORY_NO\":1,\"USER_ID_NUMBER\":\"1031523473\",\"Mobile_No\":\"0567123432\"}"

我使用了扩展名:

extension String{
func tooDictionary() -> NSDictionary {
    let blankDict : NSDictionary = [:]
    if let data = self.data(using: .utf8)  {
        do {
            return try JSONSerialization.jsonObject(with: data, options: []) as! NSDictionary
        } catch {
            print(error.localizedDescription)
        }
    }
    return blankDict
}
}

将其转换为字典,然后将其放入对象中,但我未能做到这一点

对不起,我是swift4的新开发人员,请提供任何帮助

谢谢

1 个答案:

答案 0 :(得分:0)

使用Decodable

struct User: Decodable {

    private enum CodingKeys : String, CodingKey {
        case userNumber = "USER_NO", taskCategoryNumber = "TASK_CATEGORY_NO"
        case userName = "USER_NAME", userID = "USER_ID_NUMBER", mobileNumber = "Mobile_No"
    }

    let userNumber, taskCategoryNumber: Int
    let userName, userID, mobileNumber : String
}

let jsonString = """
{"USER_NO":1,"USER_NAME":"المسار البديل لتكنولوجيا المعلومات","TASK_CATEGORY_NO":1,"USER_ID_NUMBER":"1031523473","Mobile_No":"0567123432"}
"""

let data = Data(jsonString.utf8)
do {
    let result = try JSONDecoder().decode(User.self, from: data)
    print(result)
} catch { print(error) }

注意:不要在Swift中使用NSArray / NSDictionary