简体   繁体   中英

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

I am new to the swift language. I am trying to fetching some data from an API call and response to that API is "{"status":1,"msg":"Please enter Mobile number"}"

I have the above response in a string How can I convert this string to JSONObject and then parse it and get status value?

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

I suggest use SwiftyJson library. first create a model from your json using http://jsoncafe.com

you can parse data and model it using the following code

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

then you have access to your variable => message.status

JSONSerialization is the tool you are looking for. It handles converting JSON into objects, and objects into JSON. If you receive a JSON string represented as Data , you can pass it into JSONSerialization.jsonObject(with:options:)

If you are wanting to convert Data into an 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:

//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

Create a model and use the decodable protocol

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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