Why is NSSArray not populating when parsing JSONArray? - iphone

I'm a noob to iphone development and I'm trying to parse the JSONArray from this link. The problem is that when this code is executed it returns that my NSArray contains only 4 values instead of 80 values that jSONArray at the link contains. Am I properly converting the NSDictionary into NSArray. Any help is greatly appreciated. I'm following this tutorial here.
//parse out the json data
NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseData //1
options:kNilOptions
error:&error];
NSArray* bitcoin = json; //2
NSLog(#"size of bitcoin is %lu", sizeof(bitcoin));
// 1) Get the bitcoin rate mtgoxUSD
for(int i = 0; i < sizeof(bitcoin); i++){
NSDictionary* forex = [bitcoin objectAtIndex:i];
NSString *mtgoxUSD = [forex objectForKey:#"symbol"];
NSLog(#"value against mtgoxUSD %#", mtgoxUSD);
if (mtgoxUSD==#"mtgoxUSD") {
NSString *bitcoinrate = [forex objectForKey:#"avg"];
if (bitcoinrate==#""||bitcoinrate==NULL) {
currencyBTC=1;
NSLog(#"currencyBTC: is 1");
}else{
currencyBTC=[bitcoinrate floatValue];
NSLog(#"currencyBTC: %f", currencyBTC);
}
break;
}
}

sizeof will return the size of the pointer structure in bytes, that's why you always see 4 as the value.
You should use the count method instead:
for(int i = 0; i < [bitcoin count]; i++)

"Am I properly converting the NSDictionary into NSArray"
No, not quite! JSONObjectWithData can return an array or a dictionary, depending on the JSON you're parsing. In this case, your JSON has a top-level array, so you don't need to convert it at all.
So first of all, replace your first few lines with this:
NSArray* json = [NSJSONSerialization JSONObjectWithData:responseData //1
options:kNilOptions
error:&error];
You then want to iterate through your array, but your current iteration code isn't quite right. You can use the count method that pgb suggested in another answer, or alternatively you can use the really nifty 'fast enumeration' feature of Objective-C, which looks like this:
for id item in json {
// Will iterate through all objects in the json array, accessible via item
}

Related

NSDictionary to NSString JSON

I am trying to wrap my head around pulling a keys value from a JSON array and saving it as a String for comparison later: The following code makes my app crash when it gets to this section of code. I don't understand why.
My json array looks like so:
[{"User_Id":"CRNA000099","User_Name":"jbliz","User_Fname":"Julia"}]
My xcode:
userarray_login = [NSJSONSerialization JSONObjectWithData:dataURL options:kNilOptions error:&error];
NSDictionary* userType = [userarray_login objectForKey:#"User_Name"];
NSString *userPermission = [userType objectAtIndex:0];
if ([userPermission isEqualToString:#"jbliz"])
{
NSLog(#"I should get the avalue here: %#", userPermission);
}
I am confused between NSDictionary and NSString. Any feedback would be a
NSMutableArray *name=[[[NSMutableArray alloc] initWithArray:[userarray_login valueForKey:#"User_Name"]]retain];
// Get the only all Names into name Array from json Array
NSString *userPermission = [name objectAtIndex:0]; // get the first name from Array
if ([userPermission isEqualToString:#"jbliz"])
{
NSLog(#"I should get the avalue here: %#", userPermission);
}
Json Array : [{"User_Id":"CRNA000099","User_Name":"jbliz","User_Fname":"Julia"},{},...] an array contains Dictionaries.
for this try like,
NSArray * userarray_login = [NSJSONSerialization JSONObjectWithData:dataURL options:kNilOptions error:&error];
for (NSDictionary * dict in userarray_login) {
NSString * name = [dict objectForKey:#"User_Name"];
if ([name isEqualToString:#"jbliz"]) {
NSLog(#"Value is here: %#", name);
}
}
Your json has array of Dictionary you need to follow below steps,
//NSJSONSerialization return you array in userarray_login
userarray_login = [NSJSONSerialization JSONObjectWithData:dataURL options:kNilOptions error:&error];
//You fetch Dictionary from the array
NSDictionary* userType = [userarray_login objectAtIndex:0];
//Fetch NSString value using keyValue
NSString *userPermission = [userType objectForKey:#"User_Name"];
//String comparison
if ([userPermission isEqualToString:#"jbliz"])
{
NSLog(#"I should get the avalue here: %#", userPermission);
}
This is correct code for your stuff.

NSMutableArray to byte array to string

I have an iPad app which communicates with a webservice. There I can download an encrypted file. In a particular request I get a json with login credentials. Also in that json is a key which is used to encrypt the data.
The key looks like:
[0,44,215,1,215,88,94,150]
With the json framework I can put this key into an NSMutableArray. After that I use a AES256 code to decrypt the file. But that code needs a NSString as a key. So my question is: how can I decode that NSMutableArray into an NSString? I guess I first need to put it into an byte arary, and then put it into an NSString?
Who can help me with this one?
Thanks in advance!
Firstly, convert your array of numbers (I assume they're given as NSNumbers) into a C array using code similar to the first snippet in the accepted answer here. In other words, something similar to this:
// Test array for now -- this data will come from JSON response
NSArray* nsArray = [NSArray arrayWithObjects:[NSNumber numberWithChar:1],
[NSNumber numberWithChar:2],
nil];
char cArray[2];
// Fill C-array with ints
int count = [nsArray count];
for (int i = 0; i < count; ++i) {
cArray[i] = [[nsArray objectAtIndex:i] charValue];
}
Then create an NSString using the correct encoding:
NSString *encodedStr = [NSString stringWithCString:cArray encoding:NSUTF8StringEncoding];
Note: these are code sketches, they haven't been tested!
EDIT: changed from ints to chars.
If your array is the sequence of numbers, you can loop through it
//Assume you have created keyArray from your JSON
NSMutableString * keyString = [NSMutableString string];
for (id element in keyArray) {
[string appendFormat:#"%#", id];
}
// if you need the comma's in the string
NSMutableString * keyString = [NSMutableString string];
for (id element in keyArray) {
[string appendFormat:#"%#,", id];
}
int length = [string length];
NSRange range = NSMakeRange(0, length-1);
string = [string substringWithRange:range];

NSXMLParser rss Image urls?

I am parsing rss using nsxmlparser and I would like to get some images from the rss...how can I do that?
so here is an example of the rss
<p><img scr = "IMGURL"></p>
how can I get the "IMGURL"
thanks,
TC
Here is a quick hack - only do this if you know the strings are not going to change position. Otherwise you risk crashing.
//for demo purposes lets say your <p><img scr = "IMGURL"></p> is a string named sourceString
//chop it up into an array like this and grab it from the arrays position
//create an array
NSArray *tempArray = [sourceString componentsSeparatedByString:#"\""];
//what this has done, it has create an array of objects from your source string separated by "
//so in your tempArray you will have two objects
// objectAtIndex 0 will be: <p><img scr = you wont need this so we can ignore it
// objectAtIndex 1 will be the string you want. it will be: IMGURL
// so now you can quickly create a string from it like this
NSString * imgURL = [[tempArray objectAtIndex:1]description];
Its a quick and dirty trick... but it works! So long as the data stays the same format. Your call!
You need to use a xml parser like XQuery. The query would be: /p/img#src
You can use a function such as:
NSString *stringForXQuery(NSXMLNode *node, NSString *query)
{
NSArray *results = [node objectsForXQuery:query constants:nil error:nil];
NSUInteger howManyResults = [results count];
if (howManyResults != 1) {
return nil;
}
return [[results objectAtIndex:0] stringValue];
}
And call it like this:
NSString *imgURL = stringForXQuery([yourxmldocument rootElement], #"/p/img#src");

Help needed to parse json for iPhone

I want to parse a JSON file in my iphone app. The problem is i can parse simple json files but i am confused how to do parsing on following type of json:
[{"123":
[{ "item_id":"222",
"image_count":"2",
"image_filetype":".jpg",
"image_url":"http:\/\/someurl.jpg",
},
{"item_id":"333",
"image_count":"2",
"image_filetype":".jpg",
"image_url":"http:\/\/someurl.jpg",
}]
}]
Can some on help me how to extract all the img_urls for "123".
Thank you.
NSString *jsonString = …;
// The top-level object is an array
NSArray *array = [jsonString JSONValue];
// The first element in the array is an object containing a name-value
// pair for the key/name "123". The value is itself an array
NSArray *itemsIn123 = [[array objectAtIndex:0] objectForKey:#"123"];
// Use Key-Value Coding to get an array of all values for the key
// image_url
NSArray *imgurls = [itemsIn123 valueForKey:#"image_url"];
Edit based on comments:
Since the top-level array may consist of several objects, each object having a single name-value pair with unknown name, you need to manually iterate over the top-level array:
NSString *jsonString = …;
NSMutableArray *imgurls = [NSMutableArray array];
// The top-level object is an array
NSArray *array = [jsonString JSONValue];
// Each element in the top-level array is an object
for (NSDictionary *outerObject in array) {
// Iterate over all values in the object. Each (single) value is an array
for (NSArray *innerArray in [outerObject allValues]) {
[imgurls addObjectsFromArray:[innerArray valueForKey:#"image_url"]];
}
}
The value for the object "123" will be an NSArray of NSDictionaries. Each of these dictionaries has a key "image_url" for the image url.
The code will depend on which JSON parsing library you use, but the basics should be the same.
First you want to take the key values like 123,112,189 so we will take the keys into an array
say the structure like [ Web { 123 {image url} 112 {image url} 189 {image url} ]
so
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
SBJSON *jsonParser = [SBJSON alloc]init];
NSMutableArray *yourArray1 = [jsonParser objectWithString:responseString]copy]]autorelease;
ufArray = [[yourArray1 valueForKey:#"web"] copy];
for (NSString *s in ufArray) {
[keys addObject:[NSDictionary dictionaryWithObjectsAndKeys:s,#"keys",nil]];
}
NSLOG(#"keys :%#",keys);
// this will contain 112,123,114 etc values
initialize a NSMutableArray
finalArray = [NSMutableArray alloc]init];
for (int i = 0; i < [ufArray count]; i ++) {
yourArray1 = [ufArray valueForKey:[[keys objectAtIndex:i]valueForKey:#"keys"]];
// [keys object at indes:i] - > 123 val / next loop 112 array like that
[finalArray addObject:yourArray1];
}
[jsonParser release];
jsonParser = nil;
Hope this helps!
Well if that array was called jArray
var img_urls = [];
var jL = jArray[0][123].length;
var img_urls = [];
for(var i = 0; i < jL; i++){
img_urls[i] = jArray[0][123][i].image_url;
}
//display in console:
console.log(img_urls);
demo: http://jsfiddle.net/maniator/Vx3hu/4/
I've never used JSON before, never used iPhone before, never used Xcode before...but I would think its something along along the lines of...
//object and image for item ID 222
123: item_id(222).image_url("some_url")
or the second and following items
//hi
123: item_id(333).image_url("some_url")
However something better would be when you can extract the image without the URL by using the item ID and an image ID, so when calling the object 123, you can specify the item id and the image id, which would then output all the information you require. For instance the count, file type and the image could all be displayed.
123: item_id(222).image_id(222)
Is the data file SQL or XML? XML is usually faster! So read up on nodes.
Hope that helps.
DL.

Objective-C SBJSON: order of json array

I have an iPhone application which gets a json string from a server and parses it. It contains some data and, eg. an array of comments. But I've noticed that the order of the json array is not preserved when I parse it like this:
// parse response as json
SBJSON *jsonParser = [SBJSON new];
NSDictionary *jsonData = [jsonParser objectWithString:jsonResponse error:nil];
NSDictionary* tmpDict = [jsonData objectForKey:#"rows"];
NSLog(#"keys coming!");
NSArray* keys = [tmpDict allKeys];
for (int i = 0;i< [keys count]; i++) {
NSLog([keys objectAtIndex:i]);
}
Json structure:
{
   "pagerInfo":{
      "page":"1",
      "rowsPerPage":15,
      "rowsCount":"100"
   },
   "rows":{
      "18545":{
         "id":"18545",
         "text":"comment 1"
      },
      "22464":{
         "id":"22464",
         "text":"comment 2"
      },
      "21069":{
         "id":"21069",
         "text":"comment 3"
      },
… more items
   }
}
Does anyone know how to deal with this problem? Thank you so much!
In your example JSON there is no array but a dictionary. And in a dictionary the keys are by definition not ordered in any way. So you either need to change the code that generates the JSON to really use an array or sort the keys array in your Cocoa code, maybe like this:
NSArray *keys = [[tmpDict allKeys] sortedArrayUsingSelector: #selector(compare:)];
Using that sorted keys array you can then create a new array with the objects in the correct order:
NSMutableArray *array = [NSMutableArray arrayWithCapacity: [keys count]];
for (NSString *key in keys) {
[array addObject: [tmpDict objectForKey: key]];
}
Cocoprogrmr,
Here's what you need to do: after you have parsed out your json string and loaded that into a NSArray (i.e. where you have NSArray* keys written above), from there you could put that into a for loop where you iterate over the values in your keys array. Next, to get your nested values out, for example, to get the values of rows/text, use syntax like the following:
for (NSDictionary *myKey in keys)
{
NSLog(#"rows/text --> %#", [[myKey objectForKey:#"rows"] objectForKey:#"text"]);
}
That should do it. My syntax might not be perfect there, but you get the idea.
Andy