Help needed to parse json for iPhone - 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.

Related

Why is NSSArray not populating when parsing JSONArray?

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
}

How to create an array with particular item from a dictionary?

I have an application in which i am having the details of the members as a dictionary.i want to add an array with particular object from the dictionary.The response i am having is like this,
{
500 = {
name = baddd;
status = "<null>";
};
511 = {
name = abyj;
status = "Hi all...:-)";
};
512 = {
name = abyk;
status = fdffd;
};
}
I want to create an array with the results of name only.i have tried like this
for(int i=0;i<=self.currentChannel.memberCount;i++)
{
NSString *name=[NSString stringWithFormat:#"%#",[self.currentChannel.members objectForKey:#"name"]] ;
NSLog(#"%#",name);
[searchfriendarray addObject:name];
}
NSLog(#"%#",searchfriendarray);
but the value added is null. can anybody help me ?
Traverse objectEnumerator to get the values (inner dictionaries). Then just add the value of "name" to the resulting array. Example (assuming the dictionary is named d):
NSDictionary* d = ...
NSMutableArray* array = [NSMutableArray arrayWithCapacity:d.count];
for(NSDictionary* member in d.objectEnumerator) {
[array addObject:[member objectForKey:#"name"]];
}
Krumelur was faster than me ;) He is right by saing that you should traverse the dictionary values first. In your implementation you don't reference your counter variable i somewhere, so the NSString name is the same in each iteration.
This may help you..
// here you can get Array of Dictionary First
NSArray *arr = [[NSArray alloc] initWithContentsOfFile:#""]; // get array first from your response
NSDictionary *temp = [[NSDictionary alloc] initWithDictionary:self.currentChannel.members];
for(int i=0;i<=self.currentChannel.memberCount;i++)
{
NSDictionary *temp = [arr objectAtIndex:i];
NSString *name=[NSString stringWithFormat:#"%#",[temp objectForKey:#"name"]] ;
NSLog(#"%#",name);
[searchfriendarray addObject:name];
}
NSLog(#"%#",searchfriendarray);
Thanks.

how to store string in an array while parsing json

i m parsing a json url using SBJSON and everything works fine. the problem is if m to parse the tag "title" or bascially any other tag and store it in an array named story.. i m able to get only the last value containing the tag and not the entire list of values stored in the array named story below is the code..
- (void)viewDidLoad {
[super viewDidLoad];
jsonurl=[NSURL URLWithString:#"http://www.1040communications.net/sheeba/stepheni/iphone/stephen.json"];
jsonData=[[NSString alloc]initWithContentsOfURL:jsonurl];
jsonArray = [jsonData JSONValue];
items = [jsonArray objectForKey:#"items"];
for (NSDictionary *item in items )
{
story = [NSMutableArray array];
description1 = [NSMutableArray array];
[story addObject:[item objectForKey:#"title"]];
[description1 addObject:[item objectForKey:#"description"]];
}
NSLog(#"booom:%#",story);}
The story and description1 should be declared before the loop starts.
This line should be outside the for loop
story = [NSMutableArray array];
The NSMutableArray is being created for every item in your dictionary and hence you are getting the last value only. So you need to create the dictionary before you enter the for loop.

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

How to get key value from NSdictonary - iphone sdk

I use an API which provides me data from the web. The data is in JSON format, and is stored in a NSDictionary. Like this:
SBJSON *parser = [[SBJSON alloc] init];
dict = [[NSDictionary alloc]init];
dict = [parser objectWithString:jsonArray error:nil];
Ggb console result for: po dict
1262 = {
"feed_name" = name1;
"new_results" = 6;
"next_update" = "2010-02-16T15:22:11+01:00";
};
1993 = {
"feed_name" = name2;
"new_results" = 0;
"next_update" = "2010-02-16T09:09:00+01:00";
};
How can I access the values "1262" and "1993" and put them in a NSArray, for use in a UITableView?
First of all, SBJSON's objectWithString:error: method will return one of the folowing depending on what the root object is in the JSON message:
NSArray
NSDictionary
So, you shouldn't always assume it'll return you a dictionary unless you know for a fact what will be returned in the JSON.
Secondly, you're allocating a new NSDictionary object, but then assigning the result of the parser to your dict variable, leaking the previously allocated dictionary.
You don't need this line: dict = [[NSDictionary alloc]init];.
Finally, since the returned object is a dictionary, you can get al of the objects out of the dictionary like this:
for (NSString *key in [dict allKeys])
{
NSDictionary *feed = [dict objectForKey:key];
//do stuff with feed.
}
return [dict allKeys];