How to get values from this JSON String in Objective C, iPhone - iphone

I wanted to parse a JSON String which looks like this.
There are more code in the Json String, i am pasting a sample here.
[
{ "Mainhd":"Select The Correct Adjective From The Given Options.",
"Sub":
[
{
"quetn":"Bill is two years ___ than Wanda.",
"Answr":"1",
"optns":"1,2",
"1":"younger",
"2":"smaller"
},
{
"quetn":"France is ___ European country.",
"Answr":"2",
"optns":"1,2",
"1":"an",
"2":"a"
}]
}
]
For parsing the above JSON, I am doing like this in Objective C code.
NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSError* error;
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData: jsonData //1
options:kNilOptions
error:&error];
//NSLog(#"JSON : %#",json);
if(error){
NSLog(#"Error %#", [error localizedDescription]);
}
NSString *latestLoans = [json valueForKey:#"Mainhd"];
NSLog(#"Mainhd: %#", latestLoans); //3
NSString *sub = [json valueForKey:#"Sub"];
NSLog(#"SUB: %#", sub); //3
While executing this code, I am getting this output.
SUB: (
(
{
1 = younger;
2 = smaller;
Answr = 1;
optns = "1,2";
quetn = "Bill is two years ___ than Wanda.";
},
{
1 = an;
2 = a;
Answr = 2;
optns = "1,2";
quetn = "France is ___ European country.";
},
{
1 = gorgeous;
2 = gorgeousest;
3 = gorgeouser;
Answr = 1;
optns = "1,2,3";
quetn = "Arya is looking _______ in this dress.";
}
)
)
After that i want to get values from "SUB".
I am trying like this, but not working
NSData *myData = [NSKeyedArchiver archivedDataWithRootObject:sub];
//NSData *jsonData2 = [sub dataUsingEncoding:NSUTF8StringEncoding];
NSArray *arr = [NSJSONSerialization JSONObjectWithData:myData
options:0 error:&error];
NSLog(#"ARR: %#", arr); //3
I am getting NULL.

it's worth noting in the JSON you posted, that the value for sub is an array, so you would need to treat this as such and loop through it to get your values
[
{ "Mainhd":"Select The Correct Adjective From The Given Options.",
"Sub":
[
{
"quetn":"Bill is two years ___ than Wanda.",
"Answr":"1",
"optns":"1,2",
"1":"younger",
"2":"smaller"
},
{
"quetn":"France is ___ European country.",
"Answr":"2",
"optns":"1,2",
"1":"an",
"2":"a"
}]
}
]
So the following should point you in the right direction
NSArray *subArray = [json valueForKey:#"Sub"];
//loop array using each response as a dictionary
for (NSDictionary *key in subArray){
//log the value to console
NSLog (#"Value is %#", [key objectForKey:#"quetn");
}
Hope that helps

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

NSJSONSerialization Issue

Hi I have this code.
NSString *infoString = [NSString stringWithFormat:#"http://link.com/post.php?name=%#&street=%#&city=%#&state=%#&zip=%#&lat=%#&lon=%#", name, street, city, state, zip, str1, str2];
NSURL *infoUrl = [NSURL URLWithString:infoString];
NSData *infoData = [NSData dataWithContentsOfURL:infoUrl];
NSError *error;
responseDict = [NSJSONSerialization JSONObjectWithData:infoData options:0 error:&error];
NSString *responseString = [responseDict copy];
NSLog(#"responseDict: %#", responseString);
In the console this shows up.
2012-06-14 22:37:04.022 PartyApp[20221:fb03] responseDict: {
status = 1;
}
Is there anyway I can make an if statement to show that if the value is 1 then do this and if it's not then do this. I have tried below.
if ([responseDict objectForKey:#"status = 1"]) {
Then do this
}
But it didn't work, what am I doing wrong or what could I do?
if ([responseDict objectForKey:#"status = 1"]) {
Then do this
}
should be..
if ([responseDict objectForKey:#"status"]) {
//this will be done in case of 1
}else{
//this will be done in case of 0
}
only status is the key not your entire thing.. hoping this helps..
update: The above lines are enough because of it reeturns 1 it will proceed else in case of 0 the condition is false and will go to the else clause

IOS JSON get all values from a "JSON Dict"

i have this data structure :
{
"artistlist " : [
{
"performer" : "Gate Zero"
},
{
"performer" : "nightech"
},
{
"performer" : "Marko Fuerstenberg"
},
]
}
I read this structure from NSString into NSDictionary with this line of code:
JSON = [NSJSONSerialization JSONObjectWithData:
[[chunks objectAtIndex:1]
dataUsingEncoding:NSUTF8StringEncoding] options:
NSJSONReadingMutableContainers error: &e];
with: [JSON objectForKey:#"artistlist "] i get this structure:
(
{
performer = "Gate Zero";
},
{
performer = nightech;
},
{
performer = "Marko Fuerstenberg";
}
)
Is there any way to go "deeper" ?
how would i parse the resulting Structure ?
I would like to get a list of values or access performer names directly. What if i have several values in a tupel for example performer name, album, year. How would i access those values?
Thank you.
Yes, after you have [JSON objectForKey:#"artistlist "], you get an NSArray of NSDictionaries (slightly confusing!).
NSArray *performersArray = [JSON objectForKey:#"artistlist"];
for (NSDictionary *performerDic in performersArray) {
NSLog(#"%#", [performerDic objectForKey:#"performer"]);
}
This should yield each performer name. Alternatively, you can do for (NSUInteger i = 0; i < [performersArray count]; i++) and access NSDictionary *performersDic = [performersArray objectAtIndex: i]. From there, you can similarly use [performsDic objectForKey:#"performer"]
Like this:
[[[JSON objectForKey:#"artistlist "] objectAtIndex: 1] objectForKey:#"performer"]
It will give you "nightech".
{} corresponds to NSDictionary, [] corresponds to NSArray.
You'll have to use recursion. For example, assuming you have only nested NSDictionaries (easy to modify to work with NSArrays):
- (void) getArtistFromJsonObject:(NSDictionary *)obj {
for (NSString *key in [obj allKeys]) {
id child = [obj objectForKey:key];
if ([child isKindOfClass:[NSString class]]) {
// that's the actual string
// NSLog(#"Found artist: %#", child); // or do whatever needed
} else if ([child isKindOfClass:[NSDictionary class]]) {
[self getArtistFromJsonObject:child];
}
}
}

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.

Problem Comparing Value Returned by valueForKey Method of NSDictionary

I use TouchJSON to convert the following to an NSDictionary object
// sample JSON object
{
data = (
{
companyId = 4779;
companyName = "ABC Corporation";
},
{
companyId = 4806;
companyName = "EFG Corporation";
}
);
dataCount = 2;
success = 1;
}
NSString *src = #"http://mysite/app1/companyList.php";
NSURL *url = [[NSURL alloc] initWithString:src];
NSData *data = [[NSData alloc] initWithContentsOfURL:url];
NSError *error = nil;
NSDictionary *dic = [[CJSONDeserializer deserializer] deserializeAsDictionary:data error:&error];
int dataCount = (int) [dic valueForKey:#"dataCount"];
// This is where I have problem with. The (dataCount == 1) expression never evaluates to true even if value of dataCount from the JSON object equals to 1.
if ( dataCount == 1 ){
// do something
} else {
// do something else
}
Have I done anything wrong?
I'd appreciate any help.
[dic valueForKey:#"dataCount"] will be an NSNumber. You'll need to call -intValue on it to get an int.
int dataCount = [[dic valueForKey:#"dataCount"] intValue];
if (dataCount == 1) {
...
}