How to parse my JSON data in IOS5 - iphone

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.

Related

Need help for parsing JSON

I'm learning how to parse JSON. I've made the raywenderlich tutorial but I'm still lost with some steps. I got my own JSON :
{
"Albumvideo":{
"album01":{
"titreAlbum":"Publicité",
"photoAlbum":"blabla.jpg",
"pubVideos":{
"pub01":[
{
"titrePub":"Chauffage Compris",
"dureePub":"01'25''",
"photoPub":"chauffage.jpg",
"lienPub":"http://www.wmstudio.ch/videos/chauffage.mp4"
}
]
}
},
"album02":{
"titreAlbum":"Events",
"photoAlbum":"bloublou.jpg",
"eventsVideos":{
"event01":[
{
"titreEvent":"Chauffage Compris",
"dureeEvent":"01'25''",
"photoEvent":"chauffage.jpg",
"lienEvent":"http://www.wmstudio.ch/videos/chauffage.mp4"
}
]
}
}
}
}
The I got my 'Code' to parse my JSON :
- (void) viewDidLoad
{
[super viewDidLoad];
dispatch_async (kBgQueue, ^{
NSData* data = [NSData dataWithContentsOfURL:lienAlbumsVideo];
[self performSelectorOnMainThread:#selector(fetchedData:)withObject:data waitUntilDone:YES];
});
}
- (void)fetchedData:(NSData *)responseData {
//parse out the json data
NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
NSArray* albumsVideo = [json objectForKey:#"Albumvideo"];
NSLog(#"Nombre d'albums : %i",[albumsVideo count]);
}
This works fine, my NSLog returns '2'. Where I now have difficulties is to make an array with "titreAlbum" or "event01" for example. If I do :
NSArray* event01 = [json objectForKey:#"event01"];
NSLog(#"Number of objects in event01 : %i ", [event01 count]);
My NSLog returns '0'.
I didn't really understand how to parse information from multidimensional array in a JSON. Thank's already!
Nicolas
You do not have a two-dimensional array. And JSON does not support this, but arrays of array (as C does and as Objective-C does).
NSDictionary *document = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
// Getting titreAlbum
NSDictionary *albumVideo = document[#"Albumvideo"];
NSDictionary *album01 = albumVideo[#"album01"];
NSString *titreAlbum = album01[#"titreAlbum"];
// Getting an event
NSDictionary *album02 = albumVideo[#"album02"];
NSDictionary *eventVideos = album02[#"eventsVideos"];
NSArray *event01 = eventVideo[#"event01"];
(Typped in Safari)
You can use KVC, too, if you are not interested in the middle layers.
But your identifiers and question let me think, that the structure of your JSON is malformed.
Some things,
every time you see
{ ... }
in the json that is the beginning/end of an NSDictionary
once parsed, while
[ ... ]
is the beginning end of an NSArray.
So once you parse the json using NSJSONSerialization you can navigate that dictionary using that knowledge.
Given the json you have to get an array of "titreAlbum" you would have to do something like:
NSDictionary *albumVideo = json[#"Albumvideo"];
NSMutableArray *albumTitres = [[NSMutableArray alloc] init];
for (NSDictionary *album in albumVideo) {
[albumTitres addObject:album[#"titreAlbum"]];
}
That said, I think your json is not malformed as is passing the JSONLint validation, but is not helping you to parse it. I would expect that the Albumvideo is an array of albums, instead of a dictionary of albums.
I had the same issue. I was actually trying to access Google Distance API where i needed to get
{
"routes" : [
{
"bounds" : {
"northeast" : {
"lat" : 23.0225066,
"lng" : 73.2544778
},
"southwest" : {
"lat" : 19.0718263,
"lng" : 72.57129549999999
}
},
"copyrights" : "Map data ©2014 Google",
"legs" : [
{
"distance" : {
"text" : "524 km",
"value" : 523839
},
"duration" : {
"text" : "7 hours 34 mins",
"value" : 27222
},
"end_address" : "Mumbai, Maharashtra, India",
"end_location" : {
"lat" : 19.0759856,
"lng" : 72.8776573
},
"start_address" : "Ahmedabad, Gujarat, India",
"start_location" : {
"lat" : 23.0225066,
"lng" : 72.57129549999999
},
"steps" : [
{
"distance" : {
"text" : "0.2 km",
"value" : 210
},
"duration" : {
"text" : "1 min",
"value" : 25
},
"end_location" : {
"lat" : 23.0226436,
"lng" : 72.573224
},
"html_instructions" : "Head on Swami Vivekananda RdRoad/Swami Vivekananda Rd",
"polyline" : {
"points" : "uqokCsa}yLS?GYEk#Cq##qA#eA#aADm#"
},
"start_location" : {
"lat" : 23.0225066,
"lng" : 72.57129549999999
},
"travel_mode" : "DRIVING"
}]`
I needed to access routes.legs.steps.html_instructions.
So my code is as under
NSURL *url=[[NSURL alloc] initWithString:[NSString stringWithFormat:#"http://maps.googleapis.com/maps/api/directions/json?origin=ahmedabad&destination=%#",self.city]];`
NSURLResponse *res;
NSError *err;
NSData *data=[NSURLConnection sendSynchronousRequest:[[NSURLRequest alloc] initWithURL:url] returningResponse:&res error:&err];
NSDictionary *dic=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
NSArray *routes=dic[#"routes"];
NSArray *legs=routes[0][#"legs"];
NSArray *steps=legs[0][#"steps"];
NSMutableArray *textsteps=[[NSMutableArray alloc] init];
NSMutableArray *latlong=[[NSMutableArray alloc]init];
for(int i=0; i< [steps count]; i++){
NSString *html=steps[i][#"html_instructions"];
[latlong addObject:steps[i][#"end_location"]];
[textsteps addObject:html];
}

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

Convert JSON formatted NSString to NSMutableDictionary

I have a string I'm getting from JSON.
{
"Audit_Description": "Request Approved",
"Module_Name": "Resource Request",
"Field_DisplayName": null",
"Previous_Value": Education",
"Current_Value": Employment",
"Modified_Timestamp": "08-02-2013"
},
{
"Audit_Description": "Request Approved",
"Module_Name": "Resource Request",
"Field_DisplayName": null",
"Previous_Value": null",
"Current_Value": null",
"Modified_Timestamp": "08-02-2013"
}
I want to parse data. From JSON, data come in NSString as above.
I want to extract them as key pair value. But I am not able to parse them.
This should be convert in NSMutableDictionary like
for key "Audit_Description" value should be "Request Approved"
Output:
#{
#"Audit_Description" : #"Request Approved",
#"Module_Name" = #"Resource Request",
#"Field_DisplayName" : <null>,
#"Previous_Value" : #"Education",
#"Current_Value" : #"Employment",
#"Modified_Timestamp" : #"08-02-2013"
}
Thanks.
NSError *err = nil;
NSArray *arr = [NSJSONSerialization JSONObjectWithData:[str dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:&err];
// access the dictionaries
NSMutableDictionary *dict = arr[0];
for (NSMutableDictionary *dictionary in arr) {
// do something using dictionary
}
That creates a mutable dictionary thanks to NSJSONReadingMutableContainers.

How to get data from JSON data

I have JSON like this:
[{"ID" : "351", "Name" : "Cam123 ", "camIP" : "xxx.xxx.xxx.xxx",
"Username" : "admin", "Password" : "damin", "isSupportPin" : "1" },
{"ID" : "352", "Name" : "Cam122 ", "camIP" : "xxx.xxx.xxx.xxx",
"Username" : "admin", "Password" : "damin", "isSupportPin" : "0" }
]
I want to get isSupportPin with result: 1 or 0.
if (x == 1)
{
mybutton.enabled = TRUE;
}
else
{
mybutton.enabled = FALSE;
}
How I can do it?
Assuming you have an NSData object with this data in it:
// Your JSON is an array, so I'm assuming you already know
// this and know which element you need. For the purpose
// of this example, we'll assume you want the first element
NSData* jsonData = /* assume this is your data from somewhere */
NSError* error = nil;
NSArray* array = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
if( !array ) {
// there was an error with the structure of the JSON data...
}
if( [array count] > 0 ) {
// we got our data in Foundation classes now...
NSDictionary* elementData = array[0]; // pick the correct element
// Now, extract the 'isSupportPin' attribute
NSNumber* isSupportPin = elementData[#"isSupportPin"];
// Enable the button per this item
[mybutton setEnabled:[isSupportPin boolValue]];
} else {
// Valid JSON data, but no elements... do something useful
}
The above example code snippet assumes you know which element you want to read (I guess these are user lines or something) and that you know what the JSON attribute names are (e.g., if isSupportPin isn't actually defined in the JSON object returned in that array, it will simply return nil, which will always evaluate to NO when you send it -boolValue).
Finally, the above code is written for ARC and requires Xcode 4.5 or Clang 4.1 and a deployment target of iOS 5.0. If you're not using ARC, building with a legacy version of Xcode, or targeting something earlier than 5.0, you'll have to adjust the code.
Here what you have is an NSArray of NSDictionarys. So using SBJSON library you could do as following
SBJsonParser *parser = [SBJsonParser alloc] init];
NSArray *data = [parser objectFromString:youJson];
for (NSDictionary *d in data)
{
NSString *value = [d objectForKey:#"Name"];
}
The library can be found at http://stig.github.com/json-framework/
Follow the below link that my help you.
http://www.xprogress.com/post-44-how-to-parse-json-files-on-iphone-in-objective-c-into-nsarray-and-nsdictionary/
If you want to get data or Dictionary fron JSONData then use bellow code..
NSString *responseString = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease];
NSArray *resultsArray = [responseString JSONValue];
for(NSDictionary *item in resultsArray)
{
NSDictionary *project = [item objectForKey:#"result"];//use your key name insted of result
NSLog(#"%#",project);
}
and also download JSON Library and tutorial from below link...
http://mobileorchard.com/tutorial-json-over-http-on-the-iphone/

Couldn't parse data using Json on IOS 5

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