Json Parsing at Swift with alamofire - json

I'm parsing JSON with alamofire in swift. I'm trying to look loop my json but there is something wrong with my code. When looking through code with debugger, my application wont enter at if and for. Whats wrong with my code?
I have to loop my json with "for" and parse my json data.
Alamofire.request(apiToContact, method: .get, encoding: URLEncoding.default, headers: headersq).responseJSON { (response) in
print(response)
if response.result.isSuccess {
guard let resJson = response.result.value else { return }
print(resJson);
if let json = response.result.value as? [String:AnyObject] {
for entry in json {
print("\(entry)") // this is where everything crashes
}
}
if let JSON = response.result.value as? NSDictionary{
for entry in JSON {
print("\(entry)") // this is where everything crashes
}
}
}
if response.result.isFailure {
}
}
Print(response) gives this json.:
SUCCESS: (
{
KoorX = "38.414745";
KoorY = "27.183055";
Yon = 1;
},
{
KoorX = "38.41474";
KoorY = "27.18382667";
Yon = 1;
},
{
KoorX = "38.422255";
KoorY = "27.15055167";
Yon = 1;
}
)

First of all in Swift 3+ a JSON dictionary is [String:Any]
Two issues:
The array is the value for key SUCCESS in the root object.
The fast enumeration syntax for a dictionary is for (key, value) in dictionary
guard let resJson = response.result.value as? [String:Any],
let success = resJson["SUCCESS"] as? [[String:Any]] else { return }
for entry in success {
print(entry)
}
}

This Code Help You
if let locationJSON = response.result.value
{
let locationObject: Dictionary = locationJSON as! Dictionary<String, Any>
self.dataArray = locationObject["data"]as! NSArray
}

Related

Convert JSON encoded class to dictionary for Alamofire parameters

Let's say I got the following struct
public class Response: Codable {
let status: String
let code: String
let id: String
}
What I want is to get the class properties and values as [String: Any] to send it through Alamofire like this:
let response: Response = Response(status: "A", code: "B", uuid: "C")
let data = try JSONEncoder().encode(res)
//Data to [String : Any]
Alamofire.request("endpoint", method: .post, parameters: params).responseJSON {
// Handle response
}
You can use something like this:
let response: Response = Response(status: "A", code: "B", uuid: "C")
let data = try JSONEncoder().encode(res)
//Data to [String : Any]
do {
let params = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: Any]
Alamofire.request("endpoint", method: .post, parameters: params).responseJSON {
// Handle response
}
} catch {
print(error)
}
Try using JSONSerialization as below I had used to get data from JSON
func HitApi(){
Alamofire.request(urlToGetTimeTable, method: .get, parameters: nil , encoding:URLEncoding.default).responseJSON { (response) in
if(response.result.isSuccess)
{
if let JSON = response.result.value
{
print("JSON: \(JSON)")
do {
//Clearing values in Array
self.subjectNameArray.removeAll()
//get data and serialise here to get [String:Any]
if let data = response.data,
let json = try JSONSerialization.jsonObject(with: data) as? [String: Any],
let dataDict = json["data"] as? [[String: Any]]
{
// iterate an array
for dict in dataDict
{
//get data from JSON Response
let subjectName = dict["subjects_id"] as? String
self.subjectNameArray.append(subjectName!)
}
// TableView Delegate & DataSource
// Reload TableView
self.tableView.dataSource = self;
self.tableView.delegate = self;
self.tableView.reloadData()
}
}
catch
{
//Error case
print("Error deserializing JSON: \(error)")
}
}
}
if(response.result.isFailure)
{
//Show Alert here //reason Failure
}
}
}
Give you an idea to get response as [String:Any] using son serialisation , you can use Above format in Post Method need some Modification. I deleted Rest code and showed main Code that was required

Parse Alamofire json response

I am trying to parse the response from Alamofire but I can't figure out how to do it.
This is the JSON Response I get (I want to parse out "result") how is this done?
JSON: {
result = 887957;
status = 0;
}
Swift 3
if let JSON = response.result.value {
print("JSON: \(JSON)")
}
You just need to specify the type of response is Dictionary and then use subscript with dictionary to get value of result.
if let dictionary = response.result.value as? [String: Int] {
let result = dictionary["result"] ?? 0
print(result)
}
if let JSON = response.result.value as? [String : Any] {
let result = JSON["result"] as? Int
let status = JSON["status"] as? Int
print("Result \(result) Status \(status)")
}
As per latest Almofire Lib and Swift 3.0 with proper validation:
case .success(_):
if ((response.result.value) != nil) {
var responseData = JSON(response.result.value!)
//Userdefaults helps to store session data locally just like sharedpreference in android
if (response.response ? .statusCode == 200) {
let result: Int = responseData["result"].int!
let status: Int = responseData["status"].int!
}
}
case .failure(_):
print(response.result)
}

How do I get values from a complex JSON object?

Is it possible that someone could show me how to get the names of these pizza places printing out? My application prints out the expected "Status Code: 200". However, my console only shows empty brackets []. I suspect that I am not pulling values from my JSON object properly.
I'm using this link for my API.
Link For API
Question
How can I properly fetch values from my serialized JSON object?
relevant code:
// Response
if let httpResponse = response as? NSHTTPURLResponse where httpResponse.statusCode == 200, let data = data {
print("Status Code: \(httpResponse.statusCode)")
do {
let json = try NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers)
if let pizzaPlaces = json["response"] as? [[String: AnyObject]] {
for place in pizzaPlaces {
if let name = place ["name"] as? String {
self.PizzaClass.append(name)
}
}
}
} catch {
print("Error Serializing JSON Data: \(error)")
}
print(self.PizzaClass)
}
}).resume()
You need to cast your NSJSONSerialization.JSONObjectWithData result as a [String:AnyObject].
let jsonObject = try NSJSONSerialization.JSONObjectWithData(returnedData, options: .MutableLeaves) as! [String: AnyObject]
Once you have that all you need to do is pay attention to what you're casting. Take the code below for an example. If we want to get our response object using jsonObject["response"] what kind of data structure do we have?
"response": {
"venues": [{
//... continues
}]
}
On the left we have "response" which is a string, on the right we have {} which is an AnyObject. So we have [String: AnyObject]. You just need to think about what object your dealing with piece by piece. Below is a working example that you can just paste into your application.
full working code:
func getJson() {
let request = NSMutableURLRequest(URL: NSURL(string: "https://api.foursquare.com/v2/venues/search?client_id=0F5M0EYOOFYLBXUOKTFKL5JBRZQHAQF4HEM1AG5FDX5ABRME&client_secret=FCEG5DWOASDDYII4U3AAO4DQL2O3TCN3NRZBKK01GFMVB21G&v=20130815%20&ll=29.5961,-104.2243&query=burritos")!)
let session = NSURLSession.sharedSession()
request.HTTPMethod = "GET"
request.addValue("application/json", forHTTPHeaderField: "Accept")
let task = session.dataTaskWithRequest(request) { (data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in
guard let testResponse = response as? NSHTTPURLResponse else {
print("\(response)")
return
}
guard let status = HTTPStatusCodes(rawValue: testResponse.statusCode) else {
print("failed to unwrap status")
return
}
print(status)
switch status {
case .Created:
print("ehem")
case .BadRequest:
print("bad request")
case .Ok:
print("ok")
guard let returnedData = data else {
print("no data was returned")
break
}
do {
let jsonObject = try NSJSONSerialization.JSONObjectWithData(returnedData, options: .MutableLeaves) as! [String: AnyObject]
guard let response = jsonObject["response"] as? [String: AnyObject] else { return }
guard let venues = response["venues"] as? [AnyObject] else { return }
guard let location = venues[0]["location"] as? [String:AnyObject] else { return }
guard let formattedAddress = location["formattedAddress"] else { return }
print("response: \n\n \(response)\n------")
print("venues : \n\n \(venues)\n-------")
print("location : \n\n \(location)\n------")
print("formatted address : \n \(formattedAddress)")
} catch let error {
print(error)
}
// update user interface
dispatch_sync(dispatch_get_main_queue()) {
print("update your interface on the main thread")
}
}
}
task.resume()
}
place this either in its own file our outside of the class declaration,
enum HTTPStatusCodes : Int {
case Created = 202
case Ok = 200
case BadRequest = 404
}
Not that this was what you are looking for, but since you are new to Swift take a look at Alamofire. It handles JSON serialization for you. And when you need to chain calls PromiseKit is super slick.
Alamofire.request(.GET, url).responseJSON {response in
switch (response.result) {
case .Success(let value):
let pizzas = JSON(value).arrayValue
for place in pizzaPlaces {
if let name = place ["name"] as? String {
self.PizzaClass.append(name)
}
}
case .Failure(let error):
if let data = response.data, let dataString = String(data: data, encoding: NSUTF8StringEncoding) {
print("ERROR data: \(dataString)")
}
print("ERROR: \(error)")
}
}

Swift: JSON is nil when accessing NSDictionairy

When I print(JSON) I get the files, so the .request works.
But when I am trying to access the "test" key (which exists) I get nil
I get
"I am here"
"now ,I am here"
Alamofire.request(.GET, self.APIBaseUrl , parameters: ["api_key": self.APIkey])
.responseJSON { response in
if let JSON = response.result.value {
print("I am here")
if let str = JSON as? NSDictionary {
print("now , I am here")
if let movieUrlString = str["poster_path"] as? String)! {
print("but now here")
}
EDITED
print(dict)
**dates** = {
maximum = "2015-10-21";
minimum = "2015-09-30";
};
page = 1;
**results** = (
{
adult = 0;
"poster_path" = "/2XegKZ0I4QrvzpEHneigRk6YTB1.jpg";
++(more results)
Try to use more meaningful debug printing statements and variables names. Also you were not using the right variable for subscripting. Fixed example:
Alamofire.request(.GET, self.APIBaseUrl , parameters: ["api_key": self.APIkey]).responseJSON { response in
if let JSON = response.result.value {
print("inside JSON result")
if let dict = JSON as? NSDictionary {
print("inside decoded JSON")
if let results = dict["results"] as? [NSDictionary] {
for result in results {
if let movieUrlString = result["poster_path"] as? String {
print(movieUrlString)
}
}
}
}
}
}

Grab data from JSON file doesn't work

I try to grab data from JSON (http://www.openligadb.de/api/getmatchdata/bl1/2014/15). I want to get every single game with the goals, location, team ...
I tried this but it won't work.
let url = "http://www.openligadb.de/api/getmatchdata/bl1/2014/15"
//parse url
if let JSONData = NSData(contentsOfURL: NSURL(string: url)!) {
if let json = (try? NSJSONSerialization.JSONObjectWithData(JSONData, options: [])) as? NSDictionary {
//handle json
}
}
It doesn't steps in the 2nd if-statement (if let json = (try?...).
I hope you could help me.
Edit get data of dictionaries:
//Data Team1
if let team1 = object["Team1"] as? NSDictionary {
if let name = team1["TeamName"] as? String {
print("Name Team1: \(name)")
}
if let logo = team1["TeamIconUrl"] as? String {
print("Logo Team1: \(logo)")
}
// Etc.
}
What you need to do is to understand your JSON structure: you have an array first, not a dictionary.
This array has dictionaries, each of them holding an array of dictionaries.
It may sound complex but it's actually simple, you just follow the structure of your JSON and decode the values with the correct type.
In JSON, an array starts with [ and a dictionary starts with { (also, be careful not to confuse this JSON syntax with Swift's arrays and dictionaries one).
Your code could be something like this, for example:
do {
let url = "http://www.openligadb.de/api/getmatchdata/bl1/2014/15"
if let url = NSURL(string: url),
JSONData = NSData(contentsOfURL: url),
jsonArray = try NSJSONSerialization.JSONObjectWithData(JSONData, options: []) as? NSArray {
for object in jsonArray {
if let goalsArray = object["Goals"] as? NSArray {
// Each "goal" is a dictionary
for goal in goalsArray {
print(goal)
if let name = goal["GoalGetterName"] as? String {
print("Name: \(name)")
}
if let ID = goal["GoalID"] as? Int {
print("ID: \(ID)")
}
// Etc.
}
}
}
}
} catch {
print(error)
}
UPDATE: you're almost there! But "Team1" is a dictionary, not an array. :)
Here's the solution:
do {
let url = "http://www.openligadb.de/api/getmatchdata/bl1/2014/15"
if let url = NSURL(string: url),
JSONData = NSData(contentsOfURL: url),
jsonArray = try NSJSONSerialization.JSONObjectWithData(JSONData, options: []) as? NSArray {
for object in jsonArray {
if let team1 = object["Team1"] as? NSDictionary {
if let name = team1["TeamName"] as? String {
print("Name Team1: \(name)")
}
if let logo = team1["TeamIconUrl"] as? String {
print("Logo Team1: \(logo)")
}
}
}
}
} catch {
print(error)
}