Reading from JSON file in Swift - json

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.

Related

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

Swift 3: NSArray element failed to match the Swift Array Element type

I am trying to parse JSON in swift 3 below is my JSON file. And try to get in a array of class which i have declared. But getting error: fatal error: NSArray element failed to match the Swift Array Element type.
{
"Headers": [
{
"headerName": "Home",
"sortByNo" : 1,
"headerImageName": "header0",
"viewCotrollerName": "InitialViewController"
},
{
"headerName": "About",
"sortByNo" : 2,
"headerImageName": "header1",
"viewCotrollerName": ""
},
{
"headerName": "Timing",
"sortByNo" : 3,
"headerImageName": "header3",
"viewCotrollerName": "TimingViewController"
}
]
}
// Class Type
class JsonObjectClass {
var headerName = ""
var sortByNo = ""
var headerImageName = ""
var viewControllerName = ""
}
var array = [JsonObjectClass]() // my array of class type
//JSON Parsing Code
func parseLocalFile() {
let url = Bundle.main.url(forResource: "HeaderFileD", withExtension: "json")
let data = NSData(contentsOf: url!)
do {
let jsonData = try JSONSerialization.jsonObject(with: data! as Data, options: .mutableContainers) as! NSDictionary
array = jsonData.object(forKey: "Headers") as! [JsonObjectClass]
// I am getting error here "fatal error: NSArray element failed to match the Swift Array Element type"
for arr in array {
print(arr)
}
} catch {
}
}
You cannot assign an array or dictionary to a custom class directly.
You need to map the array by creating instances of your class.
I changed the class to a struct to get the member-wise initializer. By the way, the value for key sortByNo is an Int
struct JsonObjectClass {
var headerName = ""
var sortByNo = 0
var headerImageName = ""
var viewControllerName = ""
}
var array = [JsonObjectClass]() // my array of class type
//JSON Parsing Code
func parseLocalFile() {
guard let url = Bundle.main.url(forResource: "HeaderFileD", withExtension: "json") else { return }
do {
let data = try Data(contentsOf: url)
let jsonData = try JSONSerialization.jsonObject(with: data, options: []) as! [String:Any]
let jsonArray = jsonData["Headers"] as! [[String:Any]]
array = jsonArray.map { JsonObjectClass(headerName: $0["headerName"] as! String,
sortByNo: $0["sortByNo"] as! Int,
headerImageName: $0["headerImageName"] as! String,
viewControllerName: $0["viewCotrollerName"] as! String)}
for arr in array {
print(arr)
}
} catch let error as NSError {
print(error)
}
}
PS: Consider the typo viewControllerName vs viewCotrollerName

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

swift parsing JSON data

so am trying to learn about JSON parsing, i want to extract some information from these fields..
index = 90;
property1 = {
href = "http://www.bodybuilding.com/exercises/detail/view/name/supine-one-arm-overhead-throw";
text = "Supine One-Arm Overhead Throw";
};
property2 = {
href = "http://www.bodybuilding.com/exercises/finder/lookup/filter/muscle/id/13/muscle/abdominals";
text = Abdominals;
};
property3 = (
{
href = "http://www.bodybuilding.com/exercises/detail/view/name/supine-one-arm-overhead-throw";
src = "http://www.bodybuilding.com/exercises/exerciseImages/sequences/839/Male/m/839_1.jpg";
text = "";
},
i can get a chunk of data, the problem is when i try to sort this information out... here is my code
func parseDictionary(dictionary: [String: AnyObject]) {
if let array: AnyObject = dictionary["results"] {
for resultDict in array as![AnyObject] {
if let resultDict = resultDict as? [String:AnyObject] {
if let wrapperType = resultDict["wrapperType"] as? String {
if let kind = resultDict["kind"] as? String {
print("wrapperType: \(wrapperType), kind: \(kind)")
}
}
} else {
print("expected a dictionary")
}
}
} else {
print("expected results array")
}
}
the error am getting is..
//Could not cast value of type '__NSCFDictionary' (0x1014c8a60) to //'NSArray' (0x1014c8470).
Your line:
for resultDict in array as![AnyObject] {
Needs to change to
for resultDict in array as![String: AnyObject] {
[AnyObject] is shorthand for Array<AnyObject>, whereas [String: AnyObject] is shorthand for Dictionary<String, AnyObject>, which explains your error.