I am receiving the below response from my web service?
Can any one has idea how to handle it using SBJSON?
{
"match_details" :
{
"score" : 86-1
"over" : 1.1
"runrate" : 73.71
"team_name" : England
"short_name" : ENG
"extra_run" : 50
}
"players" :
{
"key_0" :
{
"is_out" : 2
"runs" : 4
"balls" : 2
"four" : 1
"six" : 0
"batsman_name" : Ajmal Shahzad *
"wicket_info" : not out
}
"key_1" :
{
"is_out" : 1
"runs" : 12
"balls" : 6
"four" : 2
"six" : 0
"batsman_name" : Andrew Strauss
"wicket_info" : c. Kevin b.Kevin
}
"key_2" :
{
"is_out" : 2
"runs" : 20
"balls" : 7
"four" : 4
"six" : 0
"batsman_name" : Chris Tremlett *
"wicket_info" : not out
}
}
"fow" :
{
"0" : 40-1
}
}
I have done something like this:
Import SBJSON/JSON.h header file and do something like this ...
NSString *jsonResponseString = ...your JSON response...;
NSDictionary *jsonDictionary = [jsonResponseString JSONValue];
NSDictionary *players = [jsonDictionary objectForKey:#"players"];
NSDictionary *player = [players objectForKey:#"key_0"];
NSLog( #"%# %# %# %# %# %# %#", [player objectForKey:#"is_out"],
[player objectForKey:#"runs"], [player objectForKey:#"balls"],
[player objectForKey:#"four"], [player objectForKey:#"six"],
[player objectForKey:#"batsman_name"], [player objectForKey:#"wicket_info"] );
... etc.
Here is how to get the response as an array. But the main question is: What do you want to do with your data? ;)
SBJsonParser *parser = [[SBJsonParser alloc] init];
NSString * response = [request responseString];
NSMutableArray *array = [parser objectWithString:response error:nil];
NSMutableArray *match = [array valueForKey:#"match_details"];
NSMutableArray *players = [array valueForKey:#"players"];
// This should display your players name
for(id player in players) {
NSLog(#"Player name: %#", [(NSDictionary *)player valueForKey:#"batsman_name"]);
}
Related
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];
}
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/
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.
i am new programmer.i am using Google Matrix API. i get the following response i wants fetch "text" : "1686 km". i am using Json Parsing. Thanks
"destination_addresses" : [ "San Francisco, Californie, États-Unis" ],
"origin_addresses" : [ "Vancouver, BC, Canada" ],
"rows" : [
{
"elements" : [
{
"distance" : {
"text" : "1 686 km",
"value" : 1685690
},
"duration" : {
"text" : "3 jours 21 heures",
"value" : 336418
},
"status" : "OK"
}
]
}
],
"status" : "OK"
}
SBJsonParser *json = [[SBJsonParser new] autorelease];
NSError *jsonError;
parsedJSON = [json objectWithString:data error:&jsonError];
Well, parsedJSON will be an NSDictionary so:
NSArray *rows = [parsedJSON objectForKey:#"rows"];
for (NSDictionary *row in rows) {
NSArray *elements = [row objectForKey:#"elements"];
for (NSDictionary *element in elements) {
NSDictionary *distance = [element objectForKey:#"distance"];
NSString *kmDistance = [distance objectForKey:#"text"]; ///< That's what you wanted
}
}
I need to make the json params like below.
Final output should be,
{"submissionTime":"\/Date(1331549630849)\/",
"statusId":"0",
"answers":[{"answer":"Yes","qid":167},{"answer":"Hello","qid":168}],
"participantId":"16369",
"token":"t_ikHOXVjlcsSb9Tfdn5RaO54JGQobHodUD5881SKevxy63jwLxe8ZPQvXYss4pR"}
I am trying to make this format. I got the time, statusid, participantid and token. Its fine. But, i am facing problem when making "answers" array.
I use the below code for making the answers json format like below.
NSArray *answerkeys = [NSArray arrayWithObjects:#"answer", #"qid",nil];
NSString *qID = [NSString stringWithFormat:#"%d", [questionidArray objectAtIndex:i] ]; // for loop
NSArray *objectkeys = [NSArray arrayWithObjects:value, qID,nil];
NSString *answerjsonRequest = [pSr makeJSONObject:objectkeys :answerkeys];
answerjsonRequest = [(NSString *)answerjsonRequest stringByReplacingOccurrencesOfString:#"\n" withString:#""];
[textvaluesArray addObject:[NSString stringWithFormat:#"%#", answerjsonRequest]];
and the output is like below.
(
"{ \"answer\" : \"Hello\", \"qid\" : \"220421824\"}",
"{ \"answer\" : \"How are you\", \"qid\" : \"115781136\"}"
)
But, when i am adding all in one in the final output like below,
NSString *jsonRequest = [pSr makeJSONObject:[NSArray arrayWithObjects: participantID, (NULL!=textvaluesArray)?textvaluesArray:#"0", [NSString stringWithFormat:#"%d", statusID], subTime, [appDelegate getSessionToken], nil] :[NSArray arrayWithObjects:#"participantId", #"answers", #"statusId", #"submissionTime", #"token", nil] ];
The final json result is this.
{
"submissionTime" : "\/Date(1331566698)\/",
"token" : "t_hvYoxifLQhxEKfyw1CAgVtgOfA3DjeB9jZ3Laitlyk9fFdLNjJ4Cmv6K8s58iN",
"participantId" : "16371",
"answers" : [
"{ \"answer\" : \"Hello\", \"qid\" : \"220421824\"}",
"{ \"answer\" : \"Hello\", \"qid\" : \"115781136\"}"
],
"statusId" : "0"
}
BUT, this is NOT the one what i want. My expected JSON output is top above mentioned. I tried many ways, but couldn't achieve this. Could someone helping me on this to resolve to get the exact JSON output?
Thank you!
I ran into this issue as well, and created a quick category to take care of the problem.
#interface NSString (ReplaceForJSON)
- (NSString*)replaceEscapedQuotes;
#end
#implementation NSString (ReplaceForJSON)
- (NSString*)replaceEscapedQuotes
{
NSString* returnVal = [self stringByReplacingOccurrencesOfString:#"\\\"" withString:#"\""];
returnVal = [returnVal stringByReplacingOccurrencesOfString:#"\"{" withString:#"{"];
returnVal = [returnVal stringByReplacingOccurrencesOfString:#"}\"" withString:#"}"];
return returnVal;
}
#end