help me to get each elements from my json feed ? Please - iphone

I have this JSON data:
{
"data":{
"mat_149":{
"id":"149",
"title":"The closing of 40% profit within 9 month",
"teaser":"profit within 9 months only which is equal to 52% annual profit",
"body":" The auction was presented in a very high and commercial lands.\u000d\u000a",
"files":{
"911":{
"fid":"911",
"filename":"22.JPG",
"filepath":"http://mysite/files/22_0.JPG"
}
}
},
"mat_147":{
"id":"147",
"title":"Company launches the city ",
"teaser":"demands for distinguished lands.",
"body":" The area size is quare meters This is evident through projects and many other projects.\u000d\u000a\u000d\u000a",
"files":{
"906":{
"fid":"906",
"filename":"2D7z.jpg",
"filepath":"http://mysite/dlr/files/2D7Z.jpg"
}
}
},
"mat_link":"mysite.com/"
}
}
I'm parsing it like this with the json-framework:
NSString *response = [[NSString alloc] initWithData:receivedData encoding:NSASCIIStringEncoding] ;
SBJSON *parser = [[SBJSON alloc] init];
NSDictionary *data = (NSDictionary *) [parser objectWithString:response error:nil];
NSLog(#"Data : %#", [data valueForKey:#"data"] );
I am getting Data:
NSLog(#"Data : %#", [data objectForKey:#"data"] );
I am getting the data , but what i should do to get the 'file' items like 'fid' , 'filename' , 'filepath' .How can i get each elements from 'Data' n 'files' and store into some NSStrings ........
Can someone point out what I have to do ? Please

They're all sub-dictionaries aren't they,
just try logging the whole dictionary so go:
NSLog(#"%#", data);
Then you can see the structure.
To get all the other data, you're going to need to create a data model to hold it all, which knows which keys to call to get the specific strings.
Or you could call [data allKeys];
Iterating through that, getting dictionaries that you have the model object for.
E.g:
//Somewhere you declare this
NSArray *keys = [data allKeys]
for (NSString *key in [data allKeys]) {
NSDictionary *oneObject = [dictionary objectForKey:key];
MyObjectModel *object = [[MyObjectModel alloc] init];
object.id = [oneObject objectForKey:#"id"];
object.title = [oneObject objectForKey:#"title"];
//etc
//then you create another dict for files
}
Alex

Related

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

how can adding Key float values from NSDictionary to NSarray?

My brain is fried! I can't think.
i am new to iphone programming
am doing json parsing ....in that am storeing data from json to nsdictionary but .......
I want to add all nsdictionary float values from the dictionary to the array. This is what I am doing right now.As code below:
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
[connection release];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
self.responseData = nil;
dict = [responseString JSONValue];
NSMutableArray *array = [NSMutableArray array];
for (NSString *key in [dict allKeys])
{
array = [dict objectForKey:key];
// array return float values but
[array addObject:array ]; // geting carsh dude to array return float values like 120.01
}
Please guide me i am not getting a part where i am doing a mistake.
Thanks in advance.
Your app is crashing because you are adding data to NSArray , this is static array, you can not add value at run time, so just Make NSMutableArray and add your data in NSMutableArray.
Your code is broken in a couple of ways.
This line assigns the array pointer to the object in the dictionary:
array = [dict objectForKey:key];
Then you are trying to add the array to itself, which does not make sense. But worse, since array does no longer point to your NSMutableArray you cannot even call that method.
[array addObject:array ];
You probably wanted to do something like this:
for (NSString *key in [dict allKeys])
{
id value = [dict objectForKey:key];
[array addObject:value];
}

iPhone JSON Parse Problem

I'm working with parsing JSON into my app and am running into some issues pulling in just one section of it. For some reason, it seems to be going through my whole JSON feed, logging NULL values except for the one I specify.
Any advice? Thanks for the help!
My Method:
-(void)loadStats {
NSDictionary *totalsfeed = [self downloadTotals];
NSArray *totals = (NSArray *)[totalsfeed valueForKey:#"totals"];
NSLog(#"NEW TOTALS: %#", [totals valueForKey:#"d_monthly_total"]);
}
Console Results:
2011-08-30 11:35:38.096 App Name [9142:16507] NEW TOTALS: (
"<null>",
"<null>",
2,
"<null>",
"<null>",
"<null>"
)
JSON Feed
{
"totals": [
{
"ab_grand_total": "2217"
},
{
"d_grand_total": "1096"
},
{
"d_monthly_total": "2"
},
{
"ab_monthly_total": "13"
},
{
"ab_yearly_total": "746"
},
{
"d_yearly_total": "233"
}
]
}
I'm parsing the JSON here:
// JSON from Server Actions
- (NSString *)stringWithUrl:(NSURL *)url {
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url
cachePolicy:NSURLRequestReloadRevalidatingCacheData
timeoutInterval:30];
// Fetch the JSON response
NSData *urlData;
NSURLResponse *response;
NSError *error;
// Make synchronous request
urlData = [NSURLConnection sendSynchronousRequest:urlRequest
returningResponse:&response
error:&error];
// Construct a String around the Data from the response
return [[NSString alloc] initWithData:urlData encoding:NSUTF8StringEncoding];
}
- (id)objectWithUrl:(NSURL *)url {
SBJsonParser *jsonParser = [SBJsonParser new];
NSString *jsonString = [self stringWithUrl:url];
// Parse the JSON into an Object
return [jsonParser objectWithString:jsonString error:NULL];
}
- (NSDictionary *)downloadTotals {
id totals = [self objectWithUrl:[NSURL URLWithString:#"http://example.com/totals.json"]];
NSDictionary *totalsfeed = (NSDictionary *)totals;
return totalsfeed;
}
totals is an NSArray of NSDictionary objects, so [totals valueForKey:#"d_monthly_total"] does not make sense. Instead, to get d_monthly_total, you should do:
NSDictionary *dMonthlyTotalDictionary = (NSDictionary *)[totals objectAtIndex:2];
NSLog(#"NEW TOTALS: %#", [dMonthlyTotalDictionary objectForKey:"d_monthly_total"]);
To iterate through totals, do:
for(NSDictionary *myDict in totals) {
for(NSString *key in myDict) {
NSLog(#"%#: %#", key, [myDict objectForKey:key]);
}
}
Don't you have the NSDictionary and NSArray the wrong way around for the JSON you show here - wouldn't you expect the NSArray to be the outer container?
If you can control your JSON feed, you should merge these totals into a single has, e.g.:
{"ab_grand_total": "2217",
"ab_grand_total": "2217",
"d_grand_total": "1096"
}
and then load it as an NSDictionary instead of an NSArray.

key values from an NSDictionary formatting with "()"

I'm trying to pull two values from this Dictionary, But the values I'm getting have "()" around them. Any Ideas what is causing this?
Here is the ServerOutput:
{"Rows":[{"userid":"1","location":"beach"}]}
Dictionary after JSON:
{
Rows = (
{
location = beach;
userid = 1;
}
);
}
This is what I'm getting:
location : (
beach
)
user Id : (
1
)
Both the userid and the location key values have the "()". Here is the code. Thanks a lot.
NSString *serverOutput= [[NSString alloc] initWithData:dataURL encoding:NSUTF8StringEncoding];
if(serverOutput > 1){
SBJSON *jsonFF = [[SBJSON new] autorelease];
NSError *error3 = nil;
NSDictionary *useridDict= [jsonFF objectWithString:serverOutput error:&error3];
NSLog(#"useridDict: %#",useridDict);
idreturn = [[useridDict valueForKey:#"Rows"] valueForKey:#"userid"];
locationreturn = [[useridDict valueForKey:#"Rows"] valueForKey:#"location"];
NSLog(#" user Id : %#", idreturn);
NSLog(#" location : %#", locationreturn);
Just to clarify what is going on. When parsing JSON {} gets returned as a dictionary and [] gets retured as an array. So we have useridDict an NSDictionary containing the parsed data.
'useridDict' has one key Rows which returns an NSArray.
NSArray *useridArray = [useridDict objectForKey:#"Rows"];
Our useridArray has one element, an NSDictionary
NSDictionary *dict = [useridArray objectAtIndex:0];
This dict contains the two keys: location and userid
NSString *location = [dict objectForKey:#"location"];
NSInteger userid = [[dict objectForKey:#"userid"] intValue];
You can use like this.
idreturn = [[[useridDict valueForKey:#"Rows"] objectAtIndex:0]valueForKey:#"userid"];
locationreturn = [[[useridDict valueForKey:#"Rows"] objectAtIndex:0] valueForKey:#"location"];

Trying to parse twitter trends

Im trying to parse twitter trends but i keep getting a parser error at "as_of". anyone know why this is happening?
EDIT:
Here is the code im using
NSMutableArray *tweets;
tweets = [[NSMutableArray alloc] init];
NSURL *url = [NSURL URLWithString:#"http://search.twitter.com/trends/current.json"];
trendsArray = [[NSMutableArray alloc] initWithArray:[CCJSONParser objectFromJSON:[NSString stringWithContentsOfURL:url encoding:4 error:nil]]];
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
for (int i = 0; i < [trendsArray count]; i++) {
dict = [[NSMutableDictionary alloc] init];
//[post setObject: [[currentArray objectAtIndex:i] objectForKey:#"query"]];
[dict setObject:[trendsArray objectAtIndex:i] forKey:#"trends"];
//[dict setObject:[trendsArray objectAtIndex:i] forKey:#"query"];
//[post setObject:[trendsArray objectAtIndex:i] forKey:#"as_of"];
[tweets addObject:dict];
//post = nil;
}
I'm not exactly sure what your problem could be but I've had a play with the twitter api and CCJSON and have got some sample code that seems to work. If you cut and paste it into the applicationDidFinishLaunching method of a new project and include the CCJSON files it will just work (hopefully).
This code will take the trends json from twitter, output the as_of value and create an array of trends.
// Make an array to hold our trends
NSMutableArray *trends = [[NSMutableArray alloc] initWithCapacity:10];
// Get the response from the server and parse the json
NSURL *url = [NSURL URLWithString:#"http://search.twitter.com/trends/current.json"];
NSString *responseString = [NSString stringWithContentsOfURL:url encoding:4 error:nil];
NSDictionary *trendsObject = (NSDictionary *)[CCJSONParser objectFromJSON:responseString];
// Output the as_of value
NSLog(#"%#", [trendsObject objectForKey:#"as_of"]);
// We also have a list of trends (by date it seems, looking at the json)
NSDictionary *trendsList = [trendsObject objectForKey:#"trends"];
// For each date in this list
for (id key in trendsList) {
// Get the trends on this date
NSDictionary *trendsForDate = [trendsList objectForKey:key];
// For each trend in this date, add it to the trends array
for (NSDictionary *trendObject in trendsForDate) {
NSString *name = [trendObject objectForKey:#"name"];
NSString *query = [trendObject objectForKey:#"query"];
[trends addObject:[NSArray arrayWithObjects:name, query, nil]];
}
}
// At the point, we have an array called 'trends' which contains all the trends and their queries.
// Lets see it . . .
for (NSArray *array in trends)
NSLog(#"name: '%#' query: '%#'", [array objectAtIndex:0], [array objectAtIndex:1]);
Hope this is useful, comment if you have any questions,
Sam
PS I used this site to visualise the JSON response - it made it much easier to see what is going on - I just cut and paste the JSON from twitter into it :)