xcode swift 3.0 parse JSON response - ios

I'm trying to get the status code and put it in an if statement. This code will run in the xCode playground.
Right now status returns as ["200"] with square brackets around it. If I remove the brackets it returns as nil.
How to I return status as 200 and put it in an if statement?
import Foundation
let str = "{\"names\": [\"Bob\", \"Tim\", \"Tina\"],\"status\"[\"200\"],\"message\":\"User has been created\",\"id\":null,\"username\":\"asdf\"}"//"{\"names\": [\"Bob\", \"Tim\", \"Tina\"]}"
let data = str.data(using: String.Encoding.utf8, allowLossyConversion: false)!
do {
let json = try JSONSerialization.jsonObject(with: data, options: []) as! [String: AnyObject]
let status = json["status"] as? [String]
} catch let error as NSError {
print("Failed to load: \(error.localizedDescription)")
}

You can try this workaround:
let responseString = Optional("{\"status\":\"200\",\"message\":\"User has been created\",\"id\":null,\"username\":\"asdf\"}")
let responseData = responseString?.data(using: .utf8)
let dict: Dictionary<String, Any> = try JSONSerialization.jsonObject(with: responseData!, options: []) as! Dictionary<String, Any>
let status = dict["status"] // optional value stored with "status" key in Dictionary
It seems that actually, Swift 3 refuses to compile using:
let dict: Dictionary<String, Any> = try JSONSerialization.jsonObject(with: responseString?.data(using: .utf8)!, options: []) as! Dictionary<String, Any>
Swift 3 claims that responseString?.data(using: .utf8)! should be unwrapped although it is already.

let str = "{\"names\": [\"Bob\", \"Tim\", \"Tina\"],\"status\":[\"200\"],\"message\":\"User has been created\",\"id\":null,\"username\":\"asdf\"}"//"{\"names\": [\"Bob\", \"Tim\", \"Tina\"]}"
let data = str.data(using: .utf8)
do {
let json = try JSONSerialization.jsonObject(with: data!, options: []) as! [String: AnyObject]
let status = json["status"] as? [String]
let yourValue = status?[0]
} catch let error as NSError {
print("Failed to load: \(error.localizedDescription)")
}
I just add ( : ) after status in json formate to be invalid

Related

How to convert rawString to JSON Array?

I am trying to convert jsonString.rawString() to JSON object, but it returns nil.
let jsonData = newsfeedData.rawString()?.data(using: .utf8)
let object = try? JSONSerialization.jsonObject(with: jsonData!, options: .mutableContainers)
print(object) //it returns nil
This is the jsonString:
Printing description of newsfeedData.rawString:
"Data:[{\"UserID\":1,\"post\":[{\"PostId\":1,\"UserId\":1,\"UserName\":\"party Patel\",\"ImagePath\":\"/Files/User/user_20180606_040913967_Hydrangeas.jpg\",\"FileId\":2108,\"FileName\":\"Business Category.png\",\"Email\":\"parth.patel#shaligraminfotech.com\",\"Location\":\"Ahmedabad\",\"PostDescription\":\"P7800\",\"PostPath\":\"/Files/NewsFeed/Photo/fd1c7fcf-e1d0-4ffe-afb4-42bb3fea4fa4.PNG\",\"UserRole\":\"Business\",\"BusinessName\":\"Shaligram infotech\",\"PostType\":false,\"Type\":\"Photo\",\"AdminUserId\":0,\"DisplayText\":null,\"PostCreatedDate\":\"06/08/2018\",\"LikeCount\":4,\"CommentCount\":4,\"ViewCount\":3},{\"PostId\":3,\"UserId\":1,\"UserName\":\"party Patel\",\"ImagePath\":\"/Files/User/user_20180606_040913967_Hydrangeas.jpg\",\"FileId\":2110,\"FileName\":\"DiscovrUS.mov\",\"Email\":\"parth.patel#shaligraminfotech.com\",\"Location\":\"Ahmedabad\",\"PostDescription\":\"P7800\",\"PostPath\":\"/Files/NewsFeed/Video/ab48c228-d7b5-4dff-af56-31a0ac159a35.MOV\",\"UserRole\":\"Business\",\"BusinessName\":\"Shaligram infotech\",\"PostType\":true,\"Type\":\"Video\",\"AdminUserId\":0,\"DisplayText\":null,\"PostCreatedDate\":\"06/08/2018\",\"LikeCount\":1,\"CommentCount\":0,\"ViewCount\":1}]},{\"UserID\":2,\"post\":[{\"PostId\":2,\"UserId\":2,\"UserName\":\"tejas Padia\",\"ImagePath\":\"/Files/User/user_20180606_062946997_Tulips.jpg\",\"FileId\":2109,\"FileName\":\"DiscovrUS.mov\",\"Email\":\"tejaspadia#gmail.com\",\"Location\":\"India\",\"PostDescription\":\"P7800\",\"PostPath\":\"/Files/NewsFeed/Video/2d892eaf-b6dc-433d-985b-2a4588ffd307.MOV\",\"UserRole\":\"Individual\",\"BusinessName\":\"\",\"PostType\":true,\"Type\":\"Video\",\"AdminUserId\":0,\"DisplayText\":null,\"PostCreatedDate\":\"06/08/2018\",\"LikeCount\":3,\"CommentCount\":0,\"ViewCount\":0}]}]"
Make sure json format your value invalid format
just try replace Data: to empty string "" , Your code it's working
do{
var json = "Data:[{\"UserID\":1,\"post\":[{\"PostId\":1,\"UserId\":1,\"UserName\":\"party Patel\",\"ImagePath\":\"/Files/User/user_20180606_040913967_Hydrangeas.jpg\",\"FileId\":2108,\"FileName\":\"Business Category.png\",\"Email\":\"parth.patel#shaligraminfotech.com\",\"Location\":\"Ahmedabad\",\"PostDescription\":\"P7800\",\"PostPath\":\"/Files/NewsFeed/Photo/fd1c7fcf-e1d0-4ffe-afb4-42bb3fea4fa4.PNG\",\"UserRole\":\"Business\",\"BusinessName\":\"Shaligram infotech\",\"PostType\":false,\"Type\":\"Photo\",\"AdminUserId\":0,\"DisplayText\":null,\"PostCreatedDate\":\"06/08/2018\",\"LikeCount\":4,\"CommentCount\":4,\"ViewCount\":3},{\"PostId\":3,\"UserId\":1,\"UserName\":\"party Patel\",\"ImagePath\":\"/Files/User/user_20180606_040913967_Hydrangeas.jpg\",\"FileId\":2110,\"FileName\":\"DiscovrUS.mov\",\"Email\":\"parth.patel#shaligraminfotech.com\",\"Location\":\"Ahmedabad\",\"PostDescription\":\"P7800\",\"PostPath\":\"/Files/NewsFeed/Video/ab48c228-d7b5-4dff-af56-31a0ac159a35.MOV\",\"UserRole\":\"Business\",\"BusinessName\":\"Shaligram infotech\",\"PostType\":true,\"Type\":\"Video\",\"AdminUserId\":0,\"DisplayText\":null,\"PostCreatedDate\":\"06/08/2018\",\"LikeCount\":1,\"CommentCount\":0,\"ViewCount\":1}]},{\"UserID\":2,\"post\":[{\"PostId\":2,\"UserId\":2,\"UserName\":\"tejas Padia\",\"ImagePath\":\"/Files/User/user_20180606_062946997_Tulips.jpg\",\"FileId\":2109,\"FileName\":\"DiscovrUS.mov\",\"Email\":\"tejaspadia#gmail.com\",\"Location\":\"India\",\"PostDescription\":\"P7800\",\"PostPath\":\"/Files/NewsFeed/Video/2d892eaf-b6dc-433d-985b-2a4588ffd307.MOV\",\"UserRole\":\"Individual\",\"BusinessName\":\"\",\"PostType\":true,\"Type\":\"Video\",\"AdminUserId\":0,\"DisplayText\":null,\"PostCreatedDate\":\"06/08/2018\",\"LikeCount\":3,\"CommentCount\":0,\"ViewCount\":0}]}]"
json = json.replacingOccurrences(of: "Data:", with: "")
if let data = json.data(using: .utf8) {
do {
let jsonResult = try JSONSerialization.jsonObject(with: data, options: []) as? [[String: Any]]
print(jsonResult)
} catch {
print(error.localizedDescription)
}
}

Swift JSON extraction

I am developing a swift iOS app and getting the following JSON response from web service. I am trying to parse and get nextResponse from it. I am unable to extract it. Could someone guide me to solve this?
listofstudents:
({
studentsList = (
{
data = (
"32872.23",
"38814.87",
"38915.85"
);
label = “name, parents and guardians”;
}
);
dateList = (
"Apr 26, 2017",
"Jun 10, 2017",
"Jul 26, 2017"
);
firstResponse = “This school has 1432 students and 387 teachers.”;
nextResponse = “This school has around 1400 students.”;
})
Swift code:
do {
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
print("json: \(json)")
if let parseJSON = json {
let finalResponse = parseJSON["listofstudents"] as? AnyObject
print("listofstudents:: \(finalResponse)")
let nextResponse = parseJSON["nextResponse"] as? AnyObject
print("nextResponse:: \(nextResponse)")
}
} catch {
print(error)
}
Don't use NSDictionary in Swift, but use its native Swift counterpart, Dictionary. This is how you access dictionaries embedded inside other dictionaries:
do {
guard let json = try JSONSerialization.jsonObject(with: data!) as? [String:Any] else {return}
print("json: \(json)")
guard let finalResponse = parseJSON["listofstudents"] as? [String:Any] else {return}
print("listofstudents:: \(finalResponse)")
guard let nextResponse = finalResponse["nextResponse"] as? [String:Any] else {return}
print("nextResponse:: \(nextResponse)")
} catch {
print(error)
}
nextResponse is part of the JSON structure (it's a nested node). So you should access it using:
typealias JSON = [String: Any]
if let finalResponse = parseJSON["listofstudents"] as? JSON {
let nextResponse = finalResponse ["nextResponse"] as? JSON
print("nextResponse:: \(nextResponse)")
}
Looks like your listofstudents is an array of dictionary so try to iterate it and extract it:-
if let finalResponse = parseJSON["listofstudents"] as? [String: Any] {
//If your finalResponse has list then you can print all the data
for response in finalResponse {
let nextResponse = finalResponse ["nextResponse"] as? AnyObject
print("nextResponse::\(nextResponse)")
}
}

Type 'Any' doesn't conform to protocol 'Sequence'

I am having troubles in my codes, when trying to parse JSON data (each data of an array, like how it should be done) and trying to set up the for in loop, the error comes out. Here's my code
if let jsonDataArray = try? JSONSerialization.jsonObject(with: data!, options: [])
{
print(jsonDataArray)
var allStops = [busStops]()
for eachData in jsonDataArray
^
//this is where the error is located
{
if let jsonDataDictionary = eachData as? [String : AnyObject]
{
let eachStop = busStops(jsonDataDictiony: jsonDataDictionary)
}
}
}
Specify the type of jsonDataArray to directly [[String: Any]] and try like this.
if let jsonDataArray = try? JSONSerialization.jsonObject(with: data!, options: []) as? [[String: Any]] {
for eachData in jsonDataArray {
let eachStop = busStops(jsonDataDictiony: jsonDataDictionary)
}
}

Can't resolve "Ambiguous use of subscript"

I'm trying to convert a JSON response (from an NSUrlSession) into an array that I can use.
It's weird, this was working last night. However I now have a build error saying "ambiguous use of subscript".
let url = NSURL(string: "http://192.168.0.8/classes/main.php?fn=dogBoardingGet")
let task = NSURLSession.sharedSession().dataTaskWithURL(url!) {(data, response, error) in
print(NSString(data: data!, encoding: NSUTF8StringEncoding))
//var boardings = [String]()
do {
let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments)
if let theDogs = json[0] as? [[String: AnyObject]] {
for dog in theDogs {
if let ID = dog["ID"] as? String {
print(ID + " Safe")
let thisDog = Dog(name: (dog["Name"] as? String)!, surname: (dog["Surname"] as? String)!, id: (dog["ID"] as? String)!, boarding: true)
let newIndexPath = NSIndexPath(forRow: self.dogs.count, inSection: 0)
self.dogs.append(thisDog)
self.tableView.insertRowsAtIndexPaths([newIndexPath], withRowAnimation: .Bottom)
}
}
}
} catch {
print("error serializing JSON: \(error)")
}
// print(names) // ["Bloxus test", "Manila Test"]
}
task.resume()
The error is on this line: if let theDogs = json[0] as? [[String: AnyObject]] {.
From what I could tell while looking other questions, the error is because of AnyObject, so I tried to change it to [String: String]but I still get the same error.
Can anyone see the cause of this error?
Extra Information
The JSON response being received from the server:
[[{"ID":"47","Name":"Sparky","Surname":"McAllister"}]]
Looks like you are using the NSJSONSerialization, however you don't say what type of object you expect ( [AnyObject] or [String : AnyObject] ). They error you are getting is due to the fact you haven't casted to the json to [AnyObject].
PS: You might consider not using a force unwrap for the data (data!)
let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments) as! [AnyObject]

My swift app fail to convert NSData to Json

I was trying to convert NSData to Json by doing this:
let jdata = getJSON("https://api.myjson.com/bins/16j2i")
do {
let json = try NSJSONSerialization.JSONObjectWithData(jdata, options: []) as! [String: AnyObject]
print(json)
} catch {
print("\(error)")
}
This is the getJSON method
func getJSON(url:String) -> NSData {
return NSData(contentsOfURL: NSURL(string: url)!)!
}
A error says that could not cast value of type '_NSCFArray' to 'NSDictionary'. Any ideas? Please
The root element of your JSON is array not dictionary (Your format looks something like [{...},{...}] ). For fixing this error you need to change the parsing code to:
let json = try NSJSONSerialization.JSONObjectWithData(jdata, options: []) as! [[String: AnyObject]]
let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
let convert_array = responseString?.description
// Convert server json response to NSDictionary
do {
if let convertedJsonIntoDict = try JSONSerialization.jsonObject(with: data!, options: []) as? NSArray {
print(convertedJsonIntoDict)
}
let data = text.data(using: String.Encoding.utf8)
let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String:Any]
Working Fine for Swift 3.1 & Swift 4

Resources