JSON result (NSArray): valueForKey doesn't work as expected - swift

I have a NSArray as a result of a web service (JSON) request.
If I print NSLog("%#", jsonResult) the Array it shows up correctly:
(
{
text = “Some text”;
coordinates = “11.333345 - 09.33349”;
}
{
text = “Some text2”;
coordinates = “11.333345 - 09.33349”;
}
{
text = “Some text3”;
coordinates = “11.333345 - 09.33349”;
}
…
)
But If I try to access the value of the key "text" of each entry within the NSArray with my following function, I always get an output like this:
Text )r'ì• (instead of "Some text2, 3 ....")
So I think there is a mismatch of types, but I don't know how to figure out where the problem is.
In Objective-C it works very well.
func getResult(){
self.webService.getResult({ jsonResult in
jsonResult!.enumerateObjectsUsingBlock({ object, index, stop in
var txt : NSString = object.valueForKey("text") as NSString
NSLog("Text %s", txt)
})
NSLog("Ready %#", jsonResult!)
});
}
Any ideas what's going wrong?
UPDATE 1
I figured out, that if I just use NSObject instead of NSString it displays the text correct
var txt : NSObject = object.valueForKey("text") as NSObject
NSLog("%#", txt)
But anyway, I have to cast that NSObject object to NSString or String, to display...
Which encoding is it expecting to display the string...or how to cast this NSObject????

var txt : NSString = object.valueForKey("text") as NSString
NSLog("Text %s", txt)
The problem is the %s format specifier, which is for C-style strings. You need %#, which is for objects.
In Swift, it's recommended to use println(), which does away with format strings altogether:
var txt : NSString = object.valueForKey("text") as NSString
println("Text \(txt)")

Related

Could not find an overload for 'subscript' that accepts the supplied arguments in case of nsmutable array

I am new to Swift, can u plz suggest me why these errors are happening
{
var profArr : NSMutableArray = NSMutableArray()
for index in 1...<profArr.count
{
var joomlaID : NSString = [dbManager?.getZoomlaID(profArr[index]["firmUserId"] as String)];
// while using this in loop getting **could not find overload** error.
}
func getZoomlaID (firmUser : NSString) -> NSString
{
var zoomlaId : NSString
var dbPath: AnyObject? = NSUserDefaults.standardUserDefaults().valueForKey("dbPath")
var db = FMDatabase(path: dbPath as! String)
db?.open()
if var rsltSet : FMResultSet! = db!.executeQuery("Select JoomlaUserID From org_firm_users where FirmUserID like ('\(firmUser)')", withArgumentsInArray: nil) //Here again getting error Unprintable ASCII character.
{
while (rsltSet.next())
{
print(rsltSet.resultDictionary())
zoomlaId = (rsltSet.resultDictionary() as NSDictionary).valueForKey("JoomlaUserID") as! NSString
}
}
else
{
println("select failed: \(db.lastErrorMessage())")
}
db?.close()
return zoomlaId
}
}
in the line for index in 1...<profArr.count you are adding an unwanted .< to loop declaration, it should be something like this: for index in 1..profArr.count
... means from-to inclusive and .. means from-to non-inclusive.
e.g. 1..3 means 1,2,3 but 1..3 means 1,2

Json Parsing issue iOS : missing "

I got a big issue when trying to parse json data in xcode. I have actually tried with two different parser and it still returns me a wrong json. Could anyone help in that ?
The string to parse (called jsonResp) is equal to :
{
"error":false,
"errorMessage":null,
"debugMessage":null,
"count":1,
"list":"links",
"data":[
{
"date":"Jeudi \u00e0 00:00:00",
"type":"friend",
"picture":"http://graph.facebook.com/22222222/picture? type=square",
"name":"Etouda Gaudo",
"ink_id":"1",
"chat_id":"1",
"count":"1",
"last_message":"CoUcou"
}
]
}
the string to parse is equal to :
NSData *jsonData = [jsonResp dataUsingEncoding:NSUTF8StringEncoding];
NSError *error = nil;
NSDictionary *dictionary = [[CJSONDeserializer deserializer] deserializeAsDictionary:jsonData error:&error];
NSLog(#"dictionary %#", dictionary);
and then I got the following result for the NSLog of dictionary :
dictionary {
count = 1;
data = (
{
"chat_id" = 1;
count = 1;
date = "Jeudi \U00e0 00:00:00";
"ink_id" = 1;
"last_message" = CoUcou;
name = "Test name";
picture = "http://graph.facebook.com/22222222/picture?type=square";
type = friend;
}
);
debugMessage = "<null>";
error = 0;
errorMessage = "<null>";
list = links;
}
I can't figure out why the " are missing...
Does anyone have a solution.
Thanks in advance.
NSLog is just a print representation for developers to view, it is the result of the description method being called on a class instance. Quotes are only added where the item might be ambitious without them such as a string with an embedded space. To verify that the JSON was parsed correctly validate it with code.
You are deserializing the JSON into an NSDictionary, which doesn't have to have quotes around it's property names, unlike JSON. Your parser is working correctly, but the NSLog of an NSDictionary won't show up exactly the same as the original JSON would.

Decoding JSON with JSONKit gives error

I have the following JSON that validates as valid JSON..
{"flights":[{"flight":{"flightno":"BAW699","timestamp":"2011-03-22 07:06:02","route":"LOWW-EGLL"}},{"flight":{"flightno":"BAW706","timestamp":"2011-03-21 19:08:02","route":"EGLL-LOWW"}},{"flight":{"flightno":"BAW5MG","timestamp":"2011-03-21 16:33:02","route":"LEMG-EGLL"}},{"flight":{"flightno":"BAW3AG","timestamp":"2011-03-21 11:25:02","route":"EGLL-LEMG"}},{"flight":{"flightno":"BAW5EB","timestamp":"2011-03-20 19:18:02","route":"EGLL-LPPT"}},{"flight":{"flightno":"BA0489","timestamp":"2011-03-20 09:40:02","route":"LEBL-EGLL"}},{"flight":{"flightno":"BA0475","timestamp":"2011-03-19 16:51:02","route":"LEBL-EGLL"}},{"flight":{"flightno":"BAW489","timestamp":"2011-03-18 08:08:02","route":"LEBL-EGLL"}},{"flight":{"flightno":"BA0799","timestamp":"2011-03-17 18:37:02","route":"EGLL>EFHK"}},{"flight":{"flightno":"BAW799","timestamp":"2011-03-17 16:31:01","route":"EFHK-EGLL"}},{"flight":{"flightno":"BAW794","timestamp":"2011-03-17 11:55:02","route":"EGLL-EFHK"}},{"flight":{"flightno":"GEUUZ","timestamp":"2011-03-17 09:43:02","route":""}},{"flight":{"flightno":"BAW487","timestamp":"2011-03-16 19:32:01","route":"LEBL-EGLL"}},{"flight":{"flightno":"BAW486","timestamp":"2011-03-16 16:57:02","route":"EGLL-LEBL"}},{"flight":{"flightno":"BAW459","timestamp":"2011-03-16 14:10:01","route":"LEMD-EGLL"}},{"flight":{"flightno":"BAW41LM","timestamp":"2011-03-16 10:09:02","route":"EGLL-LEMD"}},{"flight":{"flightno":"BA0795","timestamp":"2011-03-16 08:27:02","route":""}},{"flight":{"flightno":"BAW795","timestamp":"2011-03-16 07:01:02","route":"EFHK-EGLL"}},{"flight":{"flightno":"BAW798","timestamp":"2011-03-15 18:23:02","route":"EGLL-EFHK"}},{"flight":{"flightno":"BAW701","timestamp":"2011-03-15 14:24:01","route":"LOWW-EGLL"}},{"flight":{"flightno":"BAW700","timestamp":"2011-03-15 11:04:01","route":"EGLL-LOWW"}},{"flight":{"flightno":"BAW68BL","timestamp":"2011-03-15 08:14:01","route":"LEBL-EGLL"}},{"flight":{"flightno":"BAW82BL","timestamp":"2011-03-14 18:40:03","route":"EGLL-LEBL"}},{"flight":{"flightno":"BAW849","timestamp":"2011-03-14 08:15:02","route":"EPWA-EGLL"}},{"flight":{"flightno":"BAW40CB","timestamp":"2011-03-13 19:30:03","route":"EGLL-LEBL"}},{"flight":{"flightno":"BAW475","timestamp":"2011-03-13 15:30:02","route":"LEBL-EGLL"}},{"flight":{"flightno":"z.NO-FLIGHTNO","timestamp":"2011-03-13 13:00:03","route":""}},{"flight":{"flightno":"BAW474","timestamp":"2011-03-13 12:00:03","route":"EGLL-LEBL"}},{"flight":{"flightno":"BAW4WP","timestamp":"2011-03-13 08:45:02","route":"LPPT-EGLL"}}]}
I then try and parse this using JSONKit but can only get as far down as "flights" I cannot seem to access the "flight" object.
When I do the following
-(void)parseJSON:(NSString *)jsonData{
NSDictionary *deserializedData = [jsonData objectFromJSONString];
for (id key in deserializedData) {
NSLog(#"key: %#, value: %#", key, [deserializedData objectForKey:key]);
}
}
Only the following is put out to the log....
key: flights, value: (
{
flight = {
flightno = BAW906N;
route = "EGLL-EDDF";
timestamp = "2011-03-24 08:38:02";
};
},
{
flight = {
flightno = BAW365;
route = "LFLL-EGLL";
timestamp = "2011-03-24 06:17:01";
};
},
{
flight = {
etc....
I want to be able to get down to each flight and at the moment am stuck!
Get an array of all flights like this:
NSArray *flights = [deserializedData valueForKeyPath:#"flights.flight"];
thats because you have an array of dictionairies in your dictionairy object, acces them like this:
for (NSDictionairy *flight in [deserializedData objectForKey:#"flights"]){
NSLog(#"flight object with route.: %#", [flight objectForKey:#"route"]);
}

Obj-C / iPhone: NSArray question

I have an array that looks like this when printed via NSLog:
{
response = "Valid";
updates = (
{
string = "test";
integer = 3493;
},
{
string = "test2";
integer = 55454;
}
);
start-index = 0;
My question is how I can loop through through the "updates" array so that I may print the values for each "string" respectively.
Should be an easy "for" loop or something?
Dave
Assuming you NSLogged data has a type of NSDictionary with name data.
NSArray *updates = [data objectForKey:#"updates"];
for (NSDictionary *update in updates) {
NSLog(#"Update: %# - %#", [update objectForKey:#"string"], [update objectForKey:#"integer"]);
}

NSString: EOL and rangeOfString issues

Could someone please tell me if I am missing something here... I am trying to parse individual JSON objects out of a data stream. The data stream is buffered in a regular NSString, and the individual JSON objects are delineated by a EOL marker.
if([dataBuffer rangeOfString:#"\n"].location != NSNotFound) {
NSString *tmp = [dataBuffer stringByReplacingOccurrencesOfString:#"\n" withString:#"NEWLINE"];
NSLog(#"%#", tmp);
}
The code above outputs "...}NEWLINE{..." as expected. But if I change the #"\n" in the if-statement above to #"}\n", I get nothing.
Why don't you use - (NSArray *)componentsSeparatedByString:(NSString *)separator? You can give it a separator of #"\n" and the result will be a convenient array of strings representing your individual JSON strings which you can then iterate over.
if([dataBuffer rangeOfString:#"\n"].location != NSNotFound) {
NSArray* JSONstrings = [dataBuffer componentsSeparatedByString:#"\n"];
for(NSString* oneString in JSONstrings)
{
// here's where you process individual JSON strings
}
}
If you do mess with the terminating '}' you could make the JSON data invalid. Just break it up and pass it to the JSON library. There could easily be a trailing space after the '}' that is causing the problem you are observing.