在Swift中解析JsonString

时间:2019-04-10 12:08:24

标签: json swift parsing

我是Swift的新手,我在JsonObject之下得到一个String,我想获取LoginStatus的值,如何解析它

{
   "ID":16,
   "NameSurname":"UĞUR ACAR",
   "LoginStatus":"True"
}

我在这里尝试解析,但是会给出错误

    func parser(_ parser: XMLParser, foundCharacters string: String) {
        if currentElementName == "LoginResult" {

            var status = ""

            do {
                let res = try JSONDecoder().decode(Root.self, from: Data(string.utf8))
                status = res.loginStatus

            } catch  {
                print("Unable to decode", error)
            }
}

1 个答案:

答案 0 :(得分:4)

您可以尝试

struct Root: Codable {
    let id: Int
    let nameSurname, loginStatus: String

    enum CodingKeys: String, CodingKey {
        case id = "ID"
        case nameSurname = "NameSurname"
        case loginStatus = "LoginStatus"
    }
}

    do {
        let res = try JSONDecoder().decode(Root.self, from: Data(jsonString.utf8))

    } catch  {
        print("Unable to decode", error)
    }