Cannot convert JSON to the correct format - ios

I'd like to use JSON output from the public Web Service https://api.rbp-zp.cz/1.3/services/district/ but looks like there is a problem with encoding in this case.
AFNetworking use to do conversion in such cases (by specific respondSerializer) like this:
var op = AFHTTPRequestOperation (request: request)
op.responseSerializer = AFJSONResponseSerializer()
but it fails because of the invalid JSON structure.
I have tried to do conversion myself, but no outcome
let rObject: AnyObject? = NSJSONSerialization.JSONObjectWithData(decodedData, options:.AllowFragments, error: nil)
When I put manually this JSON from browser to validator http://jsonlint.com, then it says it is in incorrect format.
Strangely enough when I put the JSON message from my log into the validator then the structure is valid.
Any help would be appreciated.

func convertStringToDictionary(text: String) -> [String:String]? {
if let data = text.dataUsingEncoding(NSUTF8StringEncoding) {
var error: NSError?
let json = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.allZeros, error: &error) as? [String:String]
if error != nil {
println(error)
}
return json
}
return nil
}
let str = "{\"name\":\"James\"}"
let result = convertStringToDictionary(str) // ["name": "James"]
if let name = result?["name"] { // The `?` is here because our `convertStringToDictionary` function returns an Optional
println(name) // "James"
}
In your version, you didn't pass the proper parameters to NSJSONSerialization and forgot to cast the result. Also, it's better to check for the possible error. Last note: this works only if your value is a String. If it could be another type, it would be better to declare the dictionary conversion like this:
let json = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.allZeros, error: &error) as? [String:AnyObject]
and of course you would also need to change the return type of the function:
func convertStringToDictionary(text: String) -> [String:AnyObject]? { ... }

Ok, so workaround is trimming those funny characters in the end,..don't like it much but works
let range:NSRange = NSMakeRange(0, res.length - 3);
let refinedData:NSData = res.subdataWithRange(range)
let resObject = NSJSONSerialization.JSONObjectWithData(refinedData, options:NSJSONReadingOptions.allZeros, error: &error) as! NSArray
resObject is correctly filled as NSArray now

Related

Reading Data in API response | iOS

I'm trying to integrate a login API in my iOS project. When i hit that API in browser it gives me correct JSON response. Whereas, when i call it in my app, i'm unable to read JSON. Code is as:
let url = NSURL(string: "myURL")
let request = NSURLRequest(URL: url!)
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(request) { (data, response, error) -> Void in
if error != nil {
print (error)
}
do {
//jsonDict is always nil
if let jsonDict = try self.jsonFromData(data!) {
print (jsonDict)
}
}
catch {
print ("hi")
}
}
jsonFromData is as:
private func jsonFromData(jsonData: NSData) throws -> [NSDictionary]?
{
var jsonDict: [NSDictionary]? = nil
do
{
jsonDict = try NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.AllowFragments) as? [NSDictionary]
}
catch
{
throw(error)
}
return jsonDict
}
Response of API, when hit in browser is as:
Please help me, what i am doing wrong. Thanks.
UPDATE:
I just checked that if i convert data to String, it gives correct value. i.e.
let string = NSString(data: jsonData, encoding: NSASCIIStringEncoding)
print (string)
//OUTPUT: Optional({"Authenticated":true,"CustomerID":000,"CustomerName":"TEMP","Members":[{"MemberID":000,"MemberNumber":"000","MembershipID":00,"MembershipExpiration":"\/Date(1517464799000-0600)\/","ValidBuyerTypes":[0]}]})
Look at your code where you decode the JSON and the as? statement. You are trying to get an array of NSDictionary. Your JSON as printed contains a single dictionary, not an array.
This looks right to me. The only thing I can think is that (despite what the string output looks like) the top level container of your response is NOT an NSDictionary. In your jsonFromData function, instead of assuming the result of JSONObjecWithData will be an NSDictionary, I would say:
let iDunnoWhatThisIs = try NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.AllowFragments) // don't cast this to NSDictionary
and see what you get back. It should either be a dictionary or an array, however, since you have NSJSONReadingOptions.AllowFragments set for the options, it's possible that it could be something else entirely. Start with making SURE you're actually getting back what you're assuming you are and go from there.
Try using NSKeyedUnarchiver instead:
jsonDict = NSKeyedUnarchiver.unarchiveObjectWithData(jsonData)! as NSDictionary

How To Fetch and Parse JSON Using Swift 2 + XCode 7 + iOS 9 [duplicate]

This question already has answers here:
How to parse JSON in Swift using NSURLSession
(5 answers)
Closed 7 years ago.
Was looking for useful tutorials for networking with Swift 2 and iOS 9, but it seems that topic has no content online. I have watched the WWDC session Networking with NSURLSession But I couldn't adapt the new API of iOS9 to have an asynchronous way to fetch and parse JSON data. What I have tried:
do {
if let url = NSURL(string: "site/api.php?option=fetchOps"),
let data = NSData(contentsOfURL: url),
let jsonResult = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? [[String:AnyObject]] {
}
} catch let error as NSError {
print(error.description)
}
Please share your experience with networking on iOS9 and Swift2, any best practices maybe a Singleton class for networking and parsing maybe an ORM ?
Easy way to make a request for you:
How to make an HTTP request in Swift?
Or If you want to send request by your own:
HTTP POST error Handling in Swift 2
Converting a String to JSON Object:
Just as an example, here I've converted a NSString
First of all convert the NSString to NSDictionary
static func convert(src: NSString) -> NSDictionary {
// convert String to NSData
let data = src.dataUsingEncoding(NSUTF8StringEncoding)
var error: NSError?
// convert NSData to 'AnyObject'
let anyObj: AnyObject?
do {
anyObj = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions(rawValue: 0))
} catch let error1 as NSError {
error = error1
anyObj = nil
}
if(error != nil) {
// If there is an error parsing JSON, print it to the console
print("JSON Error \(error!.localizedDescription)")
//self.showError()
return NSDictionary()
} else {
return anyObj as! NSDictionary
}
}
And then, use it like this
if let name = dictionary["name"] as? String {
self.name = name
}
You can use the converted JSON to make an object like this
import Foundation
class Student {
var name="";
init(dictionary: NSDictionary) {
let _NAME = "name"
if let name = dictionary[_NAME] as? String {
self.name = name
}
}
}
oha, well ... search for async network calls for swift. You will find many things.
But yea... Create an NSMutableRequest, init eith the URL, set the method to GET or POST.
Now make:
let task = NSURLSession.sharedSession().dataTaskWithRequest(yourMutableRequest) {
data, response, error in
// do your stuff here
}
task.resume()
This will run asynchron, so you need to think about a way to handle the data. At first your response data is in the variable data this is a type of NSData. You will need this to create your dictionary:
let dictionaryOrArray = NSJSONSerialization.JSONObjectWithData(data, options:.MutableContainers, error: nil)
Maybe you need to put this in a guard or if let statemant.
Now you need to pass the data to the function caller... you can do this in many ways, i prefer success and failure blocks
You call your Request function and you provide a success and failure block. This blocks will do what should happen in the end:
let successBlock:[AnyObject]->Void = { response in
// handle your dict
}
let failureBlock:NSError->Void = { error in
// error handling
}
YourClass.fetchSomething(someURL, parameters: params, requestMethod: method, success : successBlock, failure: failureBlock)
Something like that. In your request block with data, response, error you just do the following:
If error {
failure(error)
return
}
success(dictionaryOrArray)

Swift JSON error : Could not cast value of type '__NSDictionaryM' to 'NSArray'

when decoding JSON from webservice(API) i get error :
Could not cast value of type '__NSDictionaryM' (0x1037ad8a8) to 'NSArray' (0x1037ad470).
My Code :
var kGetURL = "http://bitnami.local/cscart_demo/api/users"
//var kGetURL = "http://localhost/fendy/getjson.php"
var json : Array<AnyObject> = []
override func viewDidLoad() {
super.viewDidLoad()
start()
}
func getData(data : NSData){
//error at this line :
json = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as! Array<AnyObject>
//error
tableView.reloadData()
}
func start(){
var url : NSURL = NSURL(string: kGetURL)!
var data : NSData = NSData(contentsOfURL: url)!
getData(data)
}
if i change url to http://localhost/fendy/getjson.php, its working so nice.
i get error if my url is http://bitnami.local/cscart_demo/api/users
Response from webservice http://localhost/fendy/getjson.php :
[{"id":"17","Name":"KFC","Message":"awesome"},
{"id":"18","Name":"McDonald","Message":"good"},
{"id":"23","Name":"Burger King","Message":"tasty"},
{"id":"38","Name":"Pizza hut","Message":"yummy"},
{"id":"39","Name":"Steak","Message":"very Delicious"}]
Response from webservice http://bitnami.local/cscart_demo/api/users :
{"users":
[{"user_id":"4","user_login":"user_4","is_root":"N","timestamp":"1441608048","user_type":"C","status":"A","firstname":"","lastname":"","email":"fendy.w#mvig.net","company":"","company_id":"1","company_name":"Simtech"},
{"user_id":"3","user_login":"customer","is_root":"N","timestamp":"1441604240","user_type":"C","status":"A","firstname":"Customer","lastname":"Customer","email":"customer#example.com","company":"Simtech","company_id":"1","company_name":"Simtech"},
{"user_id":"1","user_login":"admin","is_root":"Y","timestamp":"1441604240","user_type":"A","status":"A","firstname":"John","lastname":"Doe","email":"robby#mvig.net","company":"Your company","company_id":"0","company_name":null}],
"params":{"page":1,"items_per_page":"10","sort_order":"asc","sort_by":"name","sort_order_rev":"desc","total_items":"3"}}
i think it's Style is same, but why not working with url http://bitnami.local/cscart_demo/api/users . anyone can help?
The bitnami response starts with a { and it is therefore a JSON object, which corresponds to an NSDictionary. The other one starts with [ which indicates an array.
You need to change the type of json to Dictionary<String, AnyObject>, and deserialize as follows:
json = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as! Dictionary<String, AnyObject>
Your method is casting JSON result to an array. It works fine with the URL that returns an array represented as JSON, but it does not work with the URL that returns a dictionary, not an array, represented as JSON.
Although the "style" of returned values looks the same, the second one is a one-item dictionary. What you probably want is to extract the "users" element from it, which is an array.
If you do not know which of the two URLs you are getting, you could try both styles with as? cast instead of as!:
let tmp : AnyObject! = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil)
if let arr = tmp as? Array<AnyObject> {
json = arr
} else if dict = tmp as? [String: AnyObject] {
json = dict["users"] as! Array<AnyObject>
} else {
// Handle an error: the input was unexpected
}
tableView.reloadData()
try cache for Serialization
do {
if let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String : Any] { // as? data type
if let otherDict = json["dataKey"] as? [String : Any] {
//do something
}
}
} catch {
// can't json serialization
}

Establish Error Case in NSURLConnection, JSON Parsing in Swift

I am attempting to pull information from a JSON on my website. In doing so, if there is an error with the connection, it should return that error and log it to the console. The problem I am running into is that if I turn on Airplane more or otherwise lose signal, the error: fatal error: unexpectedly found nil while unwrapping an Optional value crashes the application. Why is it returning this, when I have set conditions for the error to simply be logged? Thank you in advance!
I am unsure why the error is not being logged and preventing the application from crashing. Any pointers would be helpful.
JSONLoader.swift
import Foundation
var arrayOfMeals: [Meal] = [Meal]()
var weekDayArray = ["monday"]
func getJSON(urlToRequest: String) -> NSDictionary {
var url: NSURL = NSURL(string: urlToRequest)!
var jsonRequest: NSURLRequest = NSURLRequest(URL: url)
var jsonResponse: AutoreleasingUnsafeMutablePointer<NSURLResponse?> = nil
var error: NSError?
var dataValue: NSData = NSURLConnection.sendSynchronousRequest(jsonRequest, returningResponse: jsonResponse, error:&error)!
if error? == nil {
var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(dataValue, options: NSJSONReadingOptions.MutableContainers , error: &error) as NSDictionary
NSURLRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheData
if error? == nil {
return jsonResult
}
else {
return NSDictionary(object: "Error: Something with parsing went wrong :(", forKey: "error")
}
}
else {
return NSDictionary(object: "Error: There was an error with your connection :(", forKey: "error")
}
}
func loadJSON(jsonDictionary: NSDictionary) {
for days in weekDayArray{
var resultsArray = jsonDictionary[days] as NSArray
for obj: AnyObject in resultsArray{
let breakfast = (obj.objectForKey("breakfast")! as String)
let lunch = (obj.objectForKey("lunch")! as String)
let dinner = obj.objectForKey("dinner")! as String
let dateString = obj.objectForKey("dateString")! as String
let dayOfWeek = obj.objectForKey("dayOfWeek")! as String
let newMeal = Meal(breakfast: breakfast, lunch: lunch, dinner: dinner, dayOfWeek: dayOfWeek, dateString: dateString)
if theDays(newMeal.dateString) >= 0 {
arrayOfMeals.append(newMeal)
}
}
}
}
I expect the function getJSON to establish an NSURLConnection to the site, parse the JSON date, and return an NSDictionary. An error case is established if there is an error in the connection, then it returns the dictionary with a value explaining the error. An additional error case occurs to parse the JSON file, and returns an NSDictionary with similar error.
I expect the function loadJSON to create instances of an object Meal, which I define as having properties of breakfast, lunch, dinner, a date, and a day of the week. The values of this instance are the results of the returned NSDictionary from function getJSON. If the day is the future, append it to my arrayOfMeals. Otherwise, ignore the instance.
MealViewController
override func viewDidLoad() {
super.viewDidLoad()
var req = getJSON("http://www.seandeaton.com/meals/Mealx")
loadJSON(req)
}
MealModel.swift - to create instances of the meals
class Meal {
let breakfast: String
let lunch: String
let dinner: String
let dayOfWeek: String
let dateString: String
init(breakfast: String, lunch: String, dinner: String, dayOfWeek: String, dateString: String) {
self.breakfast = breakfast
self.lunch = lunch
self.dinner = dinner
self.dayOfWeek = dayOfWeek
self.dateString = dateString
}
}
How can I prevent the app from crashing upon failure to establish a connection and log the error message to the console? Thanks again.
The key observation is that in the call to sendSynchronousRequest in which you're retrieving the NSData, you have defined NSData to not be optional, and you appended a ! which will force the unwrapping of the optional return value. Thus if the optional NSData was nil (which would happen if there were any network problems), this code would fail.
Instead, you should simply leave the NSData as an optional (i.e. a NSData?) and check whether it was nil or not before trying to unwrap it. Thus, I might suggest something like:
func retrieveJSON(urlToRequest: String) -> NSDictionary {
let url: NSURL = NSURL(string: urlToRequest)!
let jsonRequest: NSURLRequest = NSURLRequest(URL: url)
var jsonResponse: NSURLResponse?
var error: NSError?
let dataValue = NSURLConnection.sendSynchronousRequest(jsonRequest, returningResponse: &jsonResponse, error:&error)
if dataValue != nil {
if let jsonResult = NSJSONSerialization.JSONObjectWithData(dataValue!, options: .MutableContainers, error: &error) as? NSDictionary {
return jsonResult
} else {
return [
"error": "Error: Something with parsing went wrong :(",
"localizedDescription": error?.localizedDescription ?? ""
];
}
}
else {
return [
"error": "Error: There was an error with your connection :(",
"localizedDescription": error?.localizedDescription ?? ""
];
}
}
The above will fix crashes resulting from the forced unwrapping of the optional NSData, which would have been be nil if there were networking problems. Note, you don't show us the code that calls getJSON and then subsequently calls loadJSON, but I assume you're doing the necessary checking for error handling there.
Note, I also retired the awkward AutoreleasingUnsafeMutablePointer<NSURLResponse?> construct. I also added the localizedDescription of the error to the dictionary being returned.
Personally, I'd generally return the complete NSError object and the NSURLResponse objects, so that the caller can diagnose the precise nature of the error, rather than just text descriptions.
In a more radical edit to your code, I'd suggest you generally avoid synchronous requests. Never perform synchronous requests from the main thread.
For example, you might define the method to perform the request asynchronously, like so:
func retrieveJSON(urlToRequest: String, completionHandler:(responseObject: NSDictionary?, error: NSError?) -> ()) {
let url: NSURL = NSURL(string: urlToRequest)!
let jsonRequest: NSURLRequest = NSURLRequest(URL: url)
var jsonResponse: NSURLResponse?
NSURLConnection.sendAsynchronousRequest(jsonRequest, queue: NSOperationQueue.mainQueue()) {
response, data, error in
if data == nil {
completionHandler(responseObject: nil, error: error)
} else {
var parseError: NSError?
let jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers, error: &parseError) as NSDictionary?
completionHandler(responseObject: jsonResult, error: error)
}
}
}
You'd then call it, using the "trailing closure syntax", like so:
retrieveJSON(urlString) {
responseObject, error in
if responseObject == nil {
// handle error here, e.g.
println(error)
return
}
// handle successful the `NSDictionary` object, `responseObject`, here
}
// but don't try to use the object here, because the above runs asynchronously

Unable to get the value of JSON - Swift

I tried to get the value of "seed" from json response. But i am getting nil.
Json Response:
{
"response": {
"params": {
"rows": "20",
"defType": "abc",
"seed": "381786611"
}
}
}
Swift Parsing:
if let responseHeader:AnyObject = object?["response"] as? NSDictionary {
if let t = (responseHeader["params"] as? NSDictionary){
let t1 = t["seed"] as? String
println("result is \(t1)") // This returns nil
}
}
Json Parsing
func processJsonToDictionary(object:AnyObject?) -> AnyObject?{
if object != nil {
if let data: AnyObject = object {
var parseError: NSError?
var jsonResult = NSJSONSerialization.JSONObjectWithData(object as NSData!, options: NSJSONReadingOptions.MutableContainers, error: &parseError) as? NSDictionary
if(parseError != nil){
return parseError
}
else{
return jsonResult
}
}
}
return nil
}
I am not able to get the value of t1. it always returns nil.
How can i get the value.
Also, I put a breakpoint and tried to print the value of t1. But the Xcode Keeps crashing. Why?
I think the major problem here is only accessing a JSON object in swift.
var error: NSError?
let jsonDict = NSJSONSerialization.JSONObjectWithData(jsonData, options: nil, error: &error) as NSDictionary
let resp = jsonDict["response"] as? NSDictionary
let params = resp?["params"]?["seed"]
let seed = params!! as NSString
This is just to show you how a JSON object is accessed in swift. You can ofcourse change it according to your needs to remove unwanted Optional Chaining.
For easy JSON manipulation in Swift you could try this little library. It seems pretty easy and you could do this:
var dictionary: [String: AnyObject]!
if let json = NKJSON.parse(yourNSDataObject) {
dictionary <> json[NKJSON.rootKey]
}
First confirm that the response which you are getting is in json format or in string format.
For json parsing you can use swifty json pod

Resources