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")
}
Related
I have an array of JSON data from the following call:
guard let json = (try? JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers)) as? [Any] else {
print("Not containing JSON")
return
}
when I run print(json) I get the following in the output:
[{
"CREATED_BY" = "DOMAIN\\USER";
"CREATED_DATE" = "2016-11-28T08:43:59";
STATUS = U;
"WIDGET_NUMBER" = K11;
"UPDATED_BY" = "<null>";
"UPDATED_DATE" = "<null>";
}, {
"CREATED_BY" = "DOMAIN\\USER";
"CREATED_DATE" = "2016-05-09T08:46:23";
STATUS = U;
"WIDGET_NUMBER" = 89704;
"UPDATED_BY" = "<null>";
"UPDATED_DATE" = "<null>";
}]
I am trying to get all of the WIDGETNUMBER values in the array of JSON data. The json variable is a Any type and I have not been able to convert to a struct so far. Is there an easy way to get the elements from the JSON objects?
It looks like you have an array of dictionaries
for item in json {
if let item = item as? [String: Any], let widgetNo = item["WIDGET_NUMBER"] {
print(widgetNo)
}
}
Your content is array of Dictionary, so that you must convert each element Dictionary to Json
for dic in content {
do {
let jsonData = try JSONSerialization.data(withJSONObject: dic, options: .prettyPrinted)
print(jsonData)
} catch {
print(error.localizedDescription)
}
}
Or you can read value of WIDGET_NUMBER direct from Dictionary
for dic in content {
print(dic["WIDGET_NUMBER"] ?? "Not found")
}
Joakim's answer is spot on for getting the widget number. For your struct, be sure to add something like this as an initializer to map your object.
let widgetNumber: Int
let user: String
init?(json:[String:Any]) {
guard let widgetNumber = json["WIDGET_NUMBER"] as? Int,
let user = json["CREATED_BY"] as? String else { return nil }
self.widgetNumber = widgetNumber
self.user = user
}
If you just want an array of widget numbers you could use the reduce function which iterates the dictionaries in the array and extracts the widget numbers:
Using your data I put this in a storyboard:
let json = try? JSONSerialization.jsonObject(with: data, options: .mutableLeaves) as! [[String: Any]]
let widgetNumbers = json?.reduce(into: [String]()){ (accum, dict) in
guard let widget = dict["WIDGET_NUMBER"] as? String else { return }
accum.append(widget)
}
widgetNumbers // -> ["K11", "89704"]
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
}
I'm trying to read a JSON file but I keep getting an error when I try to read the "ParsedText". First I convert the serialized JSON data to a dictionary of type [String: Any] and then I try to read the dictionary["ParsedResults"] value and convert that to a dictionary of type [String: Any] but it always fails.
Here is the JSON file:
{
ErrorDetails = "<null>";
ErrorMessage = "<null>";
IsErroredOnProcessing = 0;
OCRExitCode = 1;
ParsedResults = ( {
ErrorDetails = "";
ErrorMessage = "";
FileParseExitCode = 1;
ParsedText = "Sample text";
TextOverlay = {
HasOverlay = 0;
Lines = ( );
Message = "Text overlay is not provided as it is not requested";
};
} );
ProcessingTimeInMilliseconds = 869;
SearchablePDFURL = "Searchable PDF not generated as it was not requested.";
}
Here is part of the swift function:
do {
//create json object from data
let dictionary = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.allowFragments) as! [String: Any]
for (key, value) in dictionary {
print("KEY: \(key)")
print("VALUE: \(value)")
}
let parsedResults = dictionary["ParsedResults"] as! [String: Any]
print("parsedResults: \(parsedResults)")
} catch let error {
print("ERROR: Could not serialize jSON Data: \(error.localizedDescription)")
}
}
As already commented, your said-to-be JSON file is not in JSON format.
It seems to be in a classic text-based plist format. If you do want to read the file as is, you can use PropertyListSerialization:
import Foundation
let data = """
{
ErrorDetails = "<null>";
ErrorMessage = "<null>";
IsErroredOnProcessing = 0;
OCRExitCode = 1;
ParsedResults = ( {
ErrorDetails = "";
ErrorMessage = "";
FileParseExitCode = 1;
ParsedText = "Sample text";
TextOverlay = {
HasOverlay = 0;
Lines = ( );
Message = "Text overlay is not provided as it is not requested";
};
} );
ProcessingTimeInMilliseconds = 869;
SearchablePDFURL = "Searchable PDF not generated as it was not requested.";
}
""".data(using: .utf8)
do {
//create property list object from data
let dictionary = try PropertyListSerialization.propertyList(from: data!, options: [], format: nil) as! [String: Any]
for (key, value) in dictionary {
print("KEY: \(key)")
print("VALUE: \(value)")
}
let parsedResults = dictionary["ParsedResults"] as! [[String: Any]] //<- See Larme's comment.
print("parsedResults: \(parsedResults)")
} catch let error {
print("ERROR: Could not deserialize plist Data: \(error.localizedDescription)")
}
But I recommend you to check the part generating such files, and fix it to generate a valid JSON file.
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)
}
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)
}
}
}
}
}
}