String convert to Json Array and then parse value in swift iOS? - 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

Related

Converting attachment data string from Gmail API to Data always returns nil on iOS

I've been using this SO post (iOS - download attachment from Gmail using messageId and attachmentId) as a reference for
I've been able to make the API call, get the response data and parse out the data for the attachment:
AF.request("https://www.googleapis.com/gmail/v1/users/me/messages/\(email.id)/attachments/\(email.payload.body.attachmentId)", headers: headers)
.responseJSON
{ [self] response in
do {
let json = try JSON(data: response.data!)
let jsonDict = convertToDictionary(text: json.rawString()!)
let attachmentDataString: String? = jsonDict!["data"] as? String
Following the accepted answer in the linked post, I made sure to format my string so that it was base64 compatible:
let formattedString = attachmentDataString!.replacingOccurrences(of: " ", with: "+", options: .literal, range: nil)
And then attempt to convert that string to data:
let attachmentData = Data(base64Encoded: formattedString)
However, this object is always nil (I'm pre-checking to make sure I only run this logic on emails with attachments).
Any help appreciated!
EDIT: This is the data string before my formatting:
https://gist.github.com/narner/d7805807992fa44a30e00d6480a04164
And this is the data string after my formatting:
https://gist.github.com/narner/02c3152d1dc935985a4da8d9b7388ade

Parse JSON data with Swift, AlamoFire and SwiftyJSON

As a Swift newcomer, I am very confused about how to parse some JSON data obtained from an API. I am able to get the JSON data from the api using an alamofire request. At this point, I think I have an NSDictionary object, JSON as print(JSON) logs to console a good deal of JSON.
if let result = response.result.value {
let JSON = result as! NSDictionary
print("this is what JSON is")
print(JSON)
My question is, first, is JSON in fact an NSDictionary. Second, how would I access a value in the JSON. Do I need to first convert this to a data object. Or how do I get at the nested data.
For example, let's say the JSON looks like this:
{
"contact": {
"first": "Bob",
"second":"Jones"
}
}
I came across this code on SO:
let data = JSON(data: JSON)
print("data\(data["contact"]["first"])")
But it throws an error. I have swiftyJSON installed but happy for solution with or without it.
Thanks in advance for any suggestions
Can you try
if let result = response.result.value as? [String:Any] {
if let contact = result["contact"] as? [String:Any] {
if let first = contact["first"] as? String {
print(first)
}
}
}
also this
let data = JSON(data: JSON)
gives error because parameter should be of type Data not Dictionary
I would prefer to return Data from Alamofire request and use Decodable to parse it and convert to required model
TRY THIS!
if let data = response.data {
let jsonData = JSON(data: data)
print("data : \(jsonData["contact"]["first"].string)")
}
Swift4 introduce amazing Codable protocol.
Using Codable, we can model JSONObject or PropertyList file into equivalent Struct or Classes by writing very few lines of code.
There are many online tool available which creates model class from you JSON
(http://www.json4swift.com/)
Example
let decoder = JSONDecoder()
let parsedObject = try decoder.decode(Class.self, from: data)
You can find detail at below link:
https://developer.apple.com/documentation/foundation/archives_and_serialization/encoding_and_decoding_custom_types

Swift convert NSMutableArray in string format to NSMutableArray

Hey guys so I create a NSMutableArray send it to my mysql server convert it to base64, then when the app reads the data, it decodes the base64 code into a string format. Now im trying to convert the string back into an NSMutableArray. I cant seem to get it work heres the code that converts it to a string.
let string = String(data: (Data(base64Encoded:((data?.value(forKey: "14112017") as! NSArray)[0] as! NSDictionary)["data"] as! String)!), encoding: .utf8)!
So the answer to my question ended up converting my array to a JSONstring first which I did by using:
let jsonData: Data? = try? JSONSerialization.data(withJSONObject: UniversalArray)
let jsonString = String(data: jsonData!, encoding: .utf8)
then when retreiving it I get back my jsonString, however it has "\" which I replace using:
let cleanJsonString = myData.replacingOccurrences(of: "\\", with: "")
then to finally finish it off I just send this cleanJsonString to this function:
func convertToDictionary(text: String) -> Any? {
if let data = text.data(using: .utf8) {
do {
return try JSONSerialization.jsonObject(with: data, options: [])
} catch {
print(error.localizedDescription)
}
}
return nil
}
when calling this function I used this:
let array = convertToDictionary(text: myMutableArray) as? [AnyObject]
Thanks everyone for the amazing support, heres the answer to this bogus mess I created.
There are 2 parts to this: Serializing your array for transmission to your server, and then deserializing it from the server.
We need to see the code you use to serialize your array first. (The code that converts it to a string.) Based on what you post, it appears to be in JSON format. If so you may be able to skip the base64 encoding step, depending on what you're doing with the data. JSON is a good format for transmission to remote servers. You don't typically base64 encode JSON before transmission.
If you are receiving JSON that was then base64 encoded, you'll need to un-encode it back to data, and then use the JSONSerializer class to convert the JSON back to objects like arrays or dictionaries:
let data = Data(base64Encoded: base64DataFromServer)
guard let object = try? JSONSerialization.jsonObject(with: data) else {
return nil
}
(Note that the JSON you posted contains a dictionary as the top-level object, not an array.)

JSON response from server in Swift

I'm calling an api in swift 3. And from the api I'm getting response in JSON String format. How to convert that JSON String to Dictionary or Array in Swift. Also that JSON string contains further array's and dictionaries.
I've tried using EVReflection tool. It's only converting the upper JSON object in dictionary. The nested dictionaries and array's are still in String format.
Try something like this, response is [String: Any] so you must cast to a any type
DispatchQueue.main.async {
do {
if let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String: Any] {
let j = json as NSDictionary
guard let resp = response as? HTTPURLResponse
else {
// No response from server
return
}
if resp.statusCode == 200 {
// You can put here some callback, this is a data you need
} else {
// Here is some error
}
}
} catch {
// And this is a error from server
}
}
You should receive jsonData which you can directly try JSONSerialization.
If for any reason you receive it as json String then you have to convert that string to jsonData first
// Here you have to convert Json String to jsonData
// if it's not Json String then skip this line
let jsonData = jsonString.data(using: .utf8)
// Try to convert it to json object
do {
let json = try JSONSerialization.jsonObject(with: jsonData, options: []) as! [String : Any]
// now you can try to parse your json
} catch let error as NSError {
print(error.localizedDescription)
}
Or as #Jay mentioned use Swiftyjson

Data > JSON - Swift3 - Convert & Parse

having one heck of a time handling the response I get from my API within a Swift3 app I'm building.
In the below screenshot, I am receiving Data from an httprequest using URLSession.shared, and passing it through to the handleSuccess method ... I am having issues simply converting to a JSON obj and accessing any of the key/values ...
...
func handleSuccess(jsonResponse: Data)
{
NSLog("Handle Success: \(jsonResponse)")
do
{
let json = try JSONSerialization.jsonObject(with: jsonResponse, options: .allowFragments)
NSLog("json: \(json)")
// I simply want to:
let firstName = json["firstName"]
try to parse your json into a dictionary first :
var firstName = ""
if let dict = json as? [String : AnyObject] {
firstName = dict["firstName"] as! String
}
...
UserManager.sharedInstance.firstName = firstName

Resources