繁体   English   中英

字符串转换为 Json 数组然后解析 swift iOS 中的值?

[英]String convert to Json Array and then parse value in swift iOS?

我是 swift 语言的新手。 我正在尝试从 API 调用中获取一些数据,并响应 API 为“{“status”:1,“msg”:“请输入手机号码”}”

我在字符串中有上述响应如何将此字符串转换为 JSONObject,然后对其进行解析并获取状态值?

我是 android 开发人员,我们在调试代码时评估表达式是否有一些类似于 Xcode 的代码,所以我可以执行一些代码运行时间

我建议使用SwiftyJson库。 首先使用http://jsoncafe.com

您可以使用以下代码解析数据和 model

 let json = JSON(response)
 let message = Message(fromJson: json )

然后你可以访问你的变量 => message.status

JSONSerialization是您正在寻找的工具。 它处理将 JSON 转换为对象,并将对象转换为 JSON。 如果您收到表示为Data的 JSON 字符串,则可以将其传递给JSONSerialization.jsonObject(with:options:)

如果您想将Data转换为 object:

//Where 'data' is the data received from the API call
guard let jsonObject = try? (JSONSerialization.jsonObject(with: data, options: []) as! [String:Any]) else {
    return
}
let status = jsonObject["status"] as! Int
let message = jsonObject["msg"] as! String

如果您想将String转换为 object:

//Where 'string' is the JSON as a String
guard let jsonObject = try? (JSONSerialization.jsonObject(with: string.data(using: .utf8), options: []) as! [String:Any]) else {
    return
}
let status = jsonObject["status"] as! Int
let message = jsonObject["msg"] as! String

来源: https://developer.apple.com/documentation/foundation/jsonserialization

创建 model 并使用可解码协议

例子:-

import Foundation

let json = """
{"status":1,"msg":"Please enter Mobile number"}
""".data(using: .utf8)!


struct Model: Codable {
    let status: Int
    let msg: String
}

let decoder = JSONDecoder()

let modelData = try! decoder.decode(Model.self, from: json)

print(modelData.status)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM