how to store string in an array while parsing json - iphone

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.

Related

How do I move all the data from NSMutableArray to NSArray with a key

I have an array NSMutableArray. It contained objects from the XML file - #"time". I need to move all records from NSMutableArray with key #"time" to NSArray. This is in order that would be based on the date on the calendar is highlighted markers. How can I implement it?
If I write the code:
NSDictionary *nItem = [rasp objectAtIndex:0]; //here instead of 0, you should put the number of elements in the array, but I do not get ((
NSArray *data = [NSArray arrayWithObjects:[nItem objectForKey:#"time"], nil];
NSMutableArray is allocated only a first date from the array, index 0.
You could do something like this.
NSMutableArray* mutable = [NSMutableArray arrayWithCapacity:0];
for(NSDictionary* nItem in rasp)
{
[mutable addObject:[nItem objectForKey:#"time"]];
}
NSArray *data = [NSArray arrayWithArray:mutable];
Hope it helps!

uitableview case sensitive sections

I am wondering how to get my get the different case letters to go into the same sections...
I pass my parsed data over to a custom method that takes the array and creates the section letters as shown bellow.. I'm just not sure how to make it so that capital and non capital letters appear in the same sections and was hoping for some help.
//method to sort array and split for use with uitableview Index
- (IBAction)startSortingTheArray:(NSArray *)arrayData
{
//If you want the standard array use this code
sortedArray = arrayData;
self.letterDictionary = [NSMutableDictionary dictionary];
sectionLetterArray = [[NSMutableArray alloc] init];
//Index scrolling Iterate over values for future use
for (NSString *value in sortedArray)
{
// Get the first letter and its associated array from the dictionary.
// If the dictionary does not exist create one and associate it with the letter.
NSString *firstLetter = [value substringWithRange:NSMakeRange(0, 1)];
NSMutableArray *arrayForLetter = [letterDictionary objectForKey:firstLetter];
if (arrayForLetter == nil)
{
arrayForLetter = [NSMutableArray array];
[letterDictionary setObject:arrayForLetter forKey:firstLetter];
[sectionLetterArray addObject:firstLetter]; // This will be used to set index scroller and section titles
}
// Add the value to the array for this letter
[arrayForLetter addObject:value];
}
//Reload data in table
[self.tableView reloadData];
}
this is what it looks like atm..
The simplest solution is to always store just the uppercase (or lowercase) version of the first letter. So you could do something like:
NSString *firstLetter = [[value substringWithRange:NSMakeRange(0, 1)] uppercaseString];

How to copy one NSMutableArray to another?

I have an nsmutablearray(xmlParseArray) having values firstname and id, I want to copy only firstname into another nsmutablearray(copyArray).
How can I do this?
Assumption: your xmlParseArray contains number of objects all of which have a firstname property and and an id property
NSMutableArray* nameArray = [[xmlParseArray valueForKey: #"firstname"] mutableCopy];
// nameArray is an array you own.
-valueForKey: when sent to an array causes the message -valueForKey: to be sent to each of its elements and a new array to be constructed from the return values. The -mutableCopy ensures that the result is then turned into a mutable array as per your question.
I'm guessing you mean that the first array, xmlParseArray, contains a list of NSDictionary objects which each have objects attached to the keys "firstname" and "id". One way to accomplish that would be like this:
NSMutableArray *copyArray = [[NSMutableArray alloc] initWithCapacity:[xmlParseArray count]];
for(NSDictionary *dict in xmlParseArray)
if([dict objectForKey:#"firstname"])
[copyArray addObject:[dict objectForKey:#"firstname"]];
// ...do whatever with copyArray...
[copyArray release];
NSMutableArray *arr = [NSMutableArray arrayWithObject:[copyArray objectAtIndex:0]];
or
[arr addObject:[copyArray objectAtIndex:0]];
[arr addObject:[copyArray objectAtIndex:1]];
NSMutableArray *newArray = [oldArray mutableCopy];
or
NSMutableArray *newArray = [NSMutableArray arrayWithArray:oldArray];
be aware that the objects in the array aren't copied, just the array itself (references to objects are maintained).

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