Parse Alamofire json response - json

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)
}

Related

Swift read from JSON dictionary

I am sending an Alamofire request and inside of my completion handler I have:
if let jsonData = response.result.value {
result = jsonData
guard let data = result.data(using: .utf8) else { return}
guard let dictionary = try? JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] else {
print("Could not cast JSON content as a Dictionary<String, Any>")
return
}
print("dictionary: \(dictionary)")
if dictionary["status"] as! String == "false"{
//Do something
}
}
else{
result = "\(response.error)"
}
The result of printing dictionary is ["status":false, "value":A1]. Ultimately I want to use status for my if statement. However I get a crash on the if statement line: if dictionary["status"] as! String == "false" of Fatal error: Unexpectedly found nil while unwrapping an Optional value. I also tried changing the line to if dictionary["status"] as! Bool == false and I get the exact same error.
The json as returned from the request is:
{
"value": "A1",
"status": "false"
}
So my question is, what is the correct way to get the value for status out of dictionary?
Would something like this work?
struct jsonOut: Codable {
let value: String
let status: String
}
if let jsonData = response.result.value {
result = jsonData
guard let data = result.data(using: .utf8)
let status = try JSONDecoder().decode(jsonOut.self, from: data)
}
Since the JSON has the format:
{
"value": "A1",
"status": "false"
}
The correct way is using Codable with the same format as the JSON:
struct jsonOut: Codable {
let value: String
let status: String
}
if let jsonData = response.result.value {
result = jsonData
guard let data = result.data(using: .utf8)
let statusData = try JSONDecoder().decode(jsonOut.self, from: data)
print("status: \(statusData.status)"
}

Json Parsing at Swift with alamofire

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
}

Parsing json having object in (); using swift

How to parse below json response in swift. I want to get the value of "code"
jsonResponse : {
messages = (
{
code = "MM_777";
message = "Password wrong";
}
);
}
Done it!
if let messages = fromJsonResponse.first {
let value = messages.value as! Array<AnyObject>
let dict = value.first as? [String: Any]
print(dict!["code"] ?? "lax")
}

The JSON output does not contain a key: "value"

I have a JSON parsing issue with my Swift code below. The error I am getting says that my JSON output does not contain a key value.
My code:
Alamofire.request(url, method: .get, headers: headers).responseJSON { (response) -> Void in
let jsonValue = response.result.value as! NSDictionary
if let bpArray = jsonValue["value"] as? [NSDictionary]{
for results in bpArray {...}
Issue:
This conversion doesnt work: if let bpArray = jsonValue["value"] as? [NSDictionary]
My JSON Structure:
{
d: {
results: [
{
__metadata: {},
Key: "AFBWhULFHtKU4j4FhWCmKg==",
ParentKey: "AAAAAAAAAAAAAAAAAAAAAA==",
RootKey: "AFBWhULFHtKU4j4FhWCmKg==",
Partner: "MM-CARR-01",
Type: "2",
Description: "MM Demo Carrier Created for Single Stop / MA",
FrieghtOrder: {}
},
...
Assuming you want to access the results key so try like this:-
if let bpArray = jsonValue["results"] as? [String: AnyObject]{
//yourcode
}
Well your json structure haven't got any key named as value and that's why it's giving an error.
In order to get results array, you first need to get the object in which they are nested and for example 'g' in your case:
if let data = jsonValue["d"] as? [NSDictionary]{
if let resultsArray = data["results"] as? NSArray {
//your code
}
}
Please Use Swifty Json Pod And Try this code
pod 'SwiftyJSON'
In Your file where you get response
import SwiftyJSON
Then After Use This Code
switch response.result {
case .success(let JSON2):
print("Success with JSON: \(JSON2)")
// print("Request failed with error: \(response.response?.statusCode)")
if let response = JSON2 as? NSMutableDictionary
{
}
else if let response = JSON2 as? NSDictionary
{
if let data = response?.object(forKey: "d") as? NSDictionary
{
if let resultsArray = data?.object(forKey: "results") as? NSArray
{
}
}
}
else if JSON2 is NSArray
{
let swjson = JSON(response.result.value!)
print(swjson)
// callback(swjson,nil)
var myMutableDictionary = [AnyHashable: Any]()
myMutableDictionary["myArray"] = swjson
callback(myMutableDictionary as NSDictionary?,nil)
print("accc")
}
else if ((JSON2 as? String) != nil)
{
let userDic : [String : String] = ["quatid":JSON2 as! String]
print(userDic)
}
break
case .failure(let error):
print("Request failed with error: \(error)")
}
Remember it's better we not use NSArray & NSDictionary like things in SWIFT, SWIFT it self providing let, var keyword for various data type.
First you can create your model where you can save the data.
MyModel.swift
class MyModel: NSObject {
var ParentKey : Int?
init(jsonObject:[String:Any]) {
ParentKey = jsonObject["ParentKey"] as? String ?? ""
}
}
Viewcontroller.Swift
var myModel : [MyModel] = []
if let responseData = response["d"] as? [String:Any]{
if let dataObject = responseData["results"] as? [[String:Any]]{
self.myModel = dataObject.map({return MyModel(jsonObject: $0)})//for assigning data into model
}
}
As most people said, I was wrong with "value". Hussain's answer to using [String:AnyObject] Helped.
I am not sure if the below is neat to achieve, but it did the magic. App loaded as expected. Code expert below:
Solution:
if let bpData = jsonValue["d"] as? [String: AnyObject]{
for results in bpData {
let arrayInterim = results.value as? NSArray
for i in 0 ..< arrayInterim!.count {

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)
}
}
}
}
}
}