[英]String convert to Json Array and then parse value in swift iOS?
I am new to the swift language.我是 swift 语言的新手。 I am trying to fetching some data from an API call and response to that API is "{"status":1,"msg":"Please enter Mobile number"}"
我正在尝试从 API 调用中获取一些数据,并响应 API 为“{“status”:1,“msg”:“请输入手机号码”}”
I have the above response in a string How can I convert this string to JSONObject and then parse it and get status value?我在字符串中有上述响应如何将此字符串转换为 JSONObject,然后对其进行解析并获取状态值?
I am an android developer we have evaluate expression while debugging code is there some like in Xcode so I can execute some code run time我是 android 开发人员,我们在调试代码时评估表达式是否有一些类似于 Xcode 的代码,所以我可以执行一些代码运行时间
I suggest use SwiftyJson
library.我建议使用
SwiftyJson
库。 first create a model from your json using http://jsoncafe.com
首先使用
http://jsoncafe.com
you can parse data and model it using the following code您可以使用以下代码解析数据和 model
let json = JSON(response)
let message = Message(fromJson: json )
then you have access to your variable => message.status
然后你可以访问你的变量 =>
message.status
JSONSerialization
is the tool you are looking for. JSONSerialization
是您正在寻找的工具。 It handles converting JSON into objects, and objects into JSON.它处理将 JSON 转换为对象,并将对象转换为 JSON。 If you receive a JSON string represented as
Data
, you can pass it into JSONSerialization.jsonObject(with:options:)
如果您收到表示为
Data
的 JSON 字符串,则可以将其传递给JSONSerialization.jsonObject(with:options:)
If you are wanting to convert Data
into an object:如果您想将
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
If you are wanting to convert String
into an object:如果您想将
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
Source: https://developer.apple.com/documentation/foundation/jsonserialization来源: https://developer.apple.com/documentation/foundation/jsonserialization
Create a model and use the decodable protocol创建 model 并使用可解码协议
Example:-例子:-
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.