Couldn't parse data using Json on IOS 5 - iphone

I try to grab some data with json on ios 5. but i fail...
could someone help me and tell me why it didn't work out.
here's my implementation code
define :
#define kBgQueue dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0) //1
#define kLatestKivaLoansURL [NSURL URLWithString:#"http://jaksport.com/jarray.php"] //2
then in the viewdidload :
NSData* data = [NSData dataWithContentsOfURL:
kLatestKivaLoansURL];
[self performSelectorOnMainThread:#selector(fetchedData:)
withObject:data waitUntilDone:YES];
this is the function:
- (void)fetchedData:(NSData *)responseData {
//parse out the json data
NSError* error;
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:responseData //1
options:kNilOptions
error:&error];
NSArray* key = [json objectForKey:#"price"]; //2
NSLog(#"value: %#", key); //3
}
this is the json file:
{
"prices":
{
"price":[
{
"id":1,
"name":"Rosie Gradas",
"beer":4.5,
"cider":4.5,
"guinness":4
},
{
"id":2,
"name":"Wicked Wolf",
"beer":5,
"cider":4.5,
"guinness":4
},
{
"id":3,
"name":"Cafe Posh",
"beer":6,
"cider":5.5,
"guinness":5.5
},
{
"id":4,
"name":"My House",
"beer":16,
"cider":15.5,
"guinness":15.5
}
]
}
}
the nslog always print out null value

The error is in how you acces the objects in your JSON :
{
"prices":
{
"price":[
{
"id":1,
"name":"Rosie Gradas",
"beer":4.5,
"cider":4.5,
"guinness":4
}
}
Given a JSON like that to access the price array you use a syntax like this
NSArray *price = [[json objectForKey:#"prices"]objecForkey:#"price"];

Check the URL in web browser, Your URL is Not A proper JSON.
Link for JSON Verification : JSON Verification

Related

Converting JSON Data from NSData to NSDictionary

I have a PHP service that returns me the following response in NSData format. After converting the same into NSString using:
NSString *html = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
I get the following:
[
{
"Emp_Name": "Krishna Mamidi",
"Emp_Designation": "Driver",
"Emp_Type": "Permanent",
"Joining_Date": "05-MAR-2011",
"Salary": 10000
},
{
"Emp_Name": "Aditya Reddy",
"Emp_Designation": "supervisor",
"Emp_Type": "Permanent",
"Joining_Date": "06-MAR-2011",
"Salary": 9000
},
{
"Emp_Name": "Rajiv krishna",
"Emp_Designation": "director",
"Emp_Type": "Permanent",
"Joining_Date": "01-MAR-2011",
"Salary": 100000
}
]
The above is in correct JSON Format.
Having received the NSData format of the above, I use the following to convert the same into JSON Dictionary:
NSError *error = nil;
id jsonObject = [NSJSONSerialization
JSONObjectWithData:data
options:NSJSONWritingPrettyPrinted error:&error];
NSDictionary *deserializedDictionary = nil;
if (jsonObject != nil && error == nil)
{
if ([jsonObject isKindOfClass:[NSDictionary class]])
{
//Convert the NSData to NSDictionary in this final step
deserializedDictionary = (NSDictionary *)jsonObject;
}
}
However the "deserializedDictionary" is always null or empty. Basically it never came inside the If Loop above.
I have been trying to figure this out for a while and am not able to. Please help
Your json object is an array try with NSArray instead of NSDictionary.
Because the JSON returned is an array, not a dictionary. Try:
NSLog(#"%#", NSStringFromClass([jsonObject class]));

How to parse my JSON data in IOS5

Can anyone tell me how to parse my json data in IOS5. I'm providing my JSON data below:
{
"fieldType" : "Alphanumeric",
"fieldName" : "Name"
},{
"fieldType" : "Numeric",
"fieldName" : "Card Num"
},{
"fieldType" : "Alphanumeric",
"fieldName" : "Pin Num"
}
Also is this JSON format correct or do I need to change the JSON format? When I try to parse JSON using below code I get an error:
The operation couldn’t be completed. (Cocoa error 3840.)
The code I'm using:
NSError *error = nil;
NSData *jsonData = [filedList dataUsingEncoding:[NSString defaultCStringEncoding]];
if (jsonData)
{
id jsonObjects = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
if (error)
{
NSLog(#"error is %#", [error localizedDescription]);
// Handle Error and return
return;
}
NSArray *keys = [jsonObjects allKeys];
// values in foreach loop
for (NSString *key in keys)
{
NSLog(#"%# is %#",key, [jsonObjects objectForKey:key]);
}
}
else
{
// Handle Error
}
The JSON data is not correctly formatted. Since you have an array of items, you need to enclose this in [ ... ]:
[
{
"fieldType" : "Alphanumeric",
"fieldName" : "Name"
},{
"fieldType" : "Numeric",
"fieldName" : "Card Num"
},{
"fieldType" : "Alphanumeric",
"fieldName" : "Pin Num"
}
]
Now JSONObjectWithData gives you an NSMutableArray of NSMutableDictionary objects (because of the NSJSONReadingMutableContainers flag).
You can walk through the parsed data with
for (NSMutableDictionary *dict in jsonObjects) {
for (NSString *key in dict) {
NSLog(#"%# is %#",key, [dict objectForKey:key]);
}
}
In any type of parsing, first of all NSLog the JSON or XML string then start writing your parsing your code.
In your case as per the JSON string you mentioned its a array of dictionaries, and once you got your jsonObjects do this to get your data..
id jsonObjects = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
NSLog(#"%#",jsonObjects);
// as per your example its an array of dictionaries so
NSArray* array = (NSArray*) jsonObjects;
for(NSDictionary* dict in array)
{
NSString* obj1 = [dict objectForKey:#"fieldType"];
NSString* obj2 = [dict objectForKey:#"fieldName"];
enter code here
enter code here
}
In this way you can parse the your json string.. for more details go through this tutorial by Raywenderlich.

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.

How to detect JSON object/JSON Array on XCode using JSON-Framework

I have some problem with JSON parsing. When I hit URL, I've got JSON response like this:
//JSON 1
{ "data":
{"array":
["3",
{"array":
[
{"id":"1","message":"Hello","sender":"inot"},
{"id":"2","message":"World","sender":"inot"},
{"id":"3","message":"Hi","sender":"marza"}
]
}
]
},
"message":"MSG0001:Success",
"status":"OK"
}
But if the result of data is just 1, the JSON response is like this:
//JSON 2
{ "data":
{"array":
["3",
{"array":
{"id":"3","message":"Hi","sender":"marza"}
}
]
},
"message":"MSG0001:Success",
"status":"OK"
}
I implement this code to get the id, message and sender value, and work fine on JSON 1, but error on JSON 2. I use JSON-Framework. And the question is how to detect that the JSON response is object ({ }) or array ([ ]) ??
// Parse the string into JSON
NSDictionary *json = [myString JSONValue];
// Get all object
NSArray *items = [json valueForKeyPath:#"data.array"];
NSArray *array1 = [[items objectAtIndex:1] objectForKey:#"array"];
NSEnumerator *enumerator = [array1 objectEnumerator];
NSDictionary* item;
while (item = (NSDictionary*)[enumerator nextObject]) {
NSLog(#"id = %#",[item objectForKey:#"id"]);
NSLog(#"message = %#",[item objectForKey:#"message"]);
NSLog(#"sender = %#",[item objectForKey:#"sender"]);
}
You can use id and check if the object that you get is NSArray or NSDictionary like this:
id item = [json valueForKeyPath:#"data.array"];
if ([item isKindOfClass:[NSArray class]]) {
// item is an array
}
else if ([item isKindOfClass:[NSDictionary class]]) {
// item is a dictionary
}