Saving JSON responce to NSDictionary - iphone

This is what my JSON return;
{
"1": {
"name": "Sharon",
"telephone": "48-9929329483"
},
"2": {
"name": "Sage",
"telephone": "48-9560333267"
},
"3": {
"name": "Alex",
"telephone": "48-8467982378"
}
}
I need to save this in a NSDictionary. My workings are as follows;
NSDictionary *contentOfDictionary = [responseString JSONValue];
NSDictionary* studentDictionary = [contentDictionary objectForKey:#"1"];
NSString *nameOfStudent = [studentDictionary objectForKey:#"name"];
NSString *nameOfStudent = [studentDictionary objectForKey:#"telephone"];
NSDictionary* studentDictionary1 = [contentDictionary objectForKey:#"2"];
NSString *nameOfStudent1 = [studentDictionary objectForKey:#"name"];
NSString *nameOfStudent1 = [studentDictionary objectForKey:#"telephone"];
..... etc
So this is what i do to save the attributes to dictionaries and strings. But the problem is that i am hard-coding the key value 1,2,3 etc.. (ex: [contentDictionary objectForKey:#"2"];)
In reality i don't know how many students will the JSON file have. There might be 100 or even more. So how can i write this in a way where the code will automatically, read JSON response (all 100 records) and save it to NSDictionary and vice versa ?
note: I guess i have to use a for loop or something.

It looks like you have a dictionary in 'contentsOfDictionary' where the keys are "1", "2", ... and the values are dictionaries containing the names/telephone numbers. So you just need to iterate through all the values:
NSMutableArray *studentDictionaries = [[NSMutableArray alloc] init];
for (NSDictionary *studentDictionary in contentOfDictionary.allValues)
{
[studentDictionaries addObject:studentDictionary];
}

If each dictionary entry in your JSON response is uniquely numbered and increasing without gaps, then you could do the following:
NSMutableArray *studentDictionaries = [[NSMutableArray alloc] init];
NSUInteger index = 1;
NSDictionary *studentDictionary;
while (studentDictionary = [contentDictionary objectForKey:[NSString stringWithFormat:#"%d", index++]]) {
[studentDictionaries addObject:studentDictionary];
}

Take a look at NSJSONSerialization available since iOS5 (or SBJSON framework). You'll get your JSON parsed and embedded in obj-c objects.

Instead of using NSDictionary to store responsestring JSONValue
NSDictionary *contentOfDictionary = [responseString JSONValue];
use NSArray to store responsestring JSONValue
NSArray *arr= [responseString JSONValue];
In this way you will get the total count ,each object in the array is a dictionary which can be accessed easily.

Related

JSON Arrays and Sorting

I have this json array which I have outlined below. I want to know how I could get all the strings under the "name" key only and place in a certain array to be sorted alphabetically by name and later split into further arrays in accordance to the first letter in the names. Any guide to carrying this out will be much appreciated, thanks. I am using the json kit via github and also NSJSONserialization.
{
"proj_name": "Ant",
"id":
[
{
"name": "David"
},
{
"name": "Aaron"
}
]
},
{
"proj_name": "Dax",
"id":
[
{
"name": "Adrian"
},
{
"name": "Dan"
}
]
}
Here is sample that selects just names and sort them alphabetically. Replace responseData with your data object.
NSMutableArray *names = [[NSMutableArray alloc] init];
NSError* error;
NSArray* json = [NSJSONSerialization
JSONObjectWithData:responseData
options:kNilOptions
error:&error];
for (NSDictionary *proj in json) {
NSArray *ids = [proj objectForKey: #"id"];
for (NSDictionary *name in ids)
{
[names addObject: [name objectForKey: #"name"];
}
}
NSArray *sortedNames = [names sortedArrayUsingSelector: #selector(localizedCaseInsensitiveCompare:)];
Go to http://json.bloople.net/ in this link you can see the structure of your JSON response.
from the above response i can see the response as follow:
Project name: Dax
id : 0 name : Adrian
1 name : Dan
So you can use the NSjsonserialization class from Apple. No need to use JSON kit.
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:#"Your URL"]]];
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSLog(#"url=%#",request);
id jsonObject = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingAllowFragments error:nil];
if ([jsonObject respondsToSelector:#selector(objectForKey:)])
{
Nsstring *projectname=[jsonObject objectForKey:#"proj_name"];
NSArray *name_array=[jsonObject objectForKey:#"id"];
NSLog(#"projectname=%#",projectname);
NSLog(#"name_array=%#",name_array);
}
Assuming you've successfully parsed the JSON into an NSArray, you can simplify things pretty dramatically:
NSArray *names = [parsedArray valueForKeyPath:#"#distinctUnionOfArrays.id.name"];
The names array should now contain all of the names flattened into a single array. To sort them, you could then do:
NSArray *sortedNames = [names sortedArrayUsingDescriptors:#[[NSSortDescriptor
sortDescriptorWithKey:#"description" ascending:YES]]];
Or all at once:
NSArray *sortedNames = [[parsedArray valueForKeyPath:#"#distinctUnionOfArrays.id.name"]
sortedArrayUsingDescriptors:#[[NSSortDescriptor
sortDescriptorWithKey:#"description"
ascending:YES]]];
The sortedNames array would now contain:
<__NSArrayI 0x713ac20>(
Aaron,
Adrian,
Dan,
David
)

How to parse JSON with multiple instance in Object C [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to use NSJSONSerialization
I am testing to use the web service of my website on iphone Application.
The JSON with problem is that:
[
{
"name": "Jason1",
"age": 20
},
{
"name": "Jason2",
"age": 40
},
{
"name": "Jason3",
"age": 60
}
]
And my codes:
NSData *jasonData = [NSData dataWithContentsOfURL:[NSURL URLWithString:#"http://localhost:3000/all_personal_information.json"]];
NSDictionary *json = nil;
if (jasonData) {
json = [NSJSONSerialization JSONObjectWithData:jasonData options:kNilOptions error:nil];
}
The code work fine with {"name":"jason","age":20}
and I can get the values by using json[#"name"] and json[#"age"]
But i don't know how to get the value from the JSON with problem.
I tried to use [json enumerateKeysAndObjectsWithOptions] to transverse the dictionary.
But I will get an error:
enumerateKeysAndObjectsWithOptions:usingBlock:]: unrecognized selector sent to instance 0x89b2490
But I can get the full JSON when I Log the [json description] into console.
Take it in an array.. for example
NSData *jasonData = [NSData dataWithContentsOfURL:[NSURL URLWithString:#"http://localhost:3000/all_personal_information.json"]];
NSDictionary *json = nil;
if (jasonData) {
NSError *e = nil;
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:jasonData options:NSJSONReadingMutableContainers error: &e];
}
the array will contain your
{
"name": "Jason1",
"age": 20
}
etc in its individual indexes. when u want to get the values in it, you can use this below method to get the values
NSDictionary *userName = [jsonArray objectAtIndex:1];
NSString *stringName = [userName valueForKey:#"name"];
You're creating a dictionary while you get an array. If you do the following it should work:
id json = nil;
if (jasonData)
{
json = [NSJSONSerialization JSONObjectWithData:jasonData options:kNilOptions error:nil];
}
if ([json isKindOfClass:NSArray.class])
{
for (id personDef in json)
{
if ([personDef isKindOfClass:NSDictionary.class])
{
NSDictionary * dict = (NSDictionary *) moduleDef;
NSString * name = [dict objectForKey:#"name" withClass:NSString.class];
NSLog(#"Person: #%", name);
}
}
}
In here I do some additional checking if the objects are the ones we expect. If this isn't the case you should add (proper) error handling.
it will help you.
NSMutableDictionary *CompaintsAry =[NSJSONSerialization JSONObjectWithData:respo options:kNilOptions error:&error];
NSMutableArray *tempary =[[NSMutableArray alloc]init];
for (int i=0;i < [CompaintsAry count];i++) {
CfResultFatch *rs = [[CfResultFatch alloc] initWithName:[[CompaintsAry obj ectAtIndex:i]objectForKey:#"Name"]
cipd :[[CompaintsAry objectAtIndex:i] objectForKey:#"Age"]];
[tempary addObject:rs];
}
cfComlaintsLists = [[NSMutableArray alloc] initWithArray:tempary];
SelectComplain = [[NSMutableArray alloc] initWithCapacity:[cfComlaintsLists count]];
[chiftab reloadData];

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

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];