How to separate JSON response in iphone - iphone

I have an application in which I am having a json response like this.
{"success":"true","message":"You have logged in","pserial":"1"} and I am separating with ":".
And I am getting data like this pSerial:"1"} but I want only 1 value.
NSURL *url = [NSURL URLWithString:strUrl];
NSData *respData = [NSData dataWithContentsOfURL:url];
NSString *strResp = [[NSString alloc]initWithData:respData encoding:NSUTF8StringEncoding];
NSString *approvalString = [[strResp componentsSeparatedByString:#":"] objectAtIndex:3];
NSLog(#"pSerial:%#",approvalString);

for Example :
SBJsonParser *jsonPar = [[SBJsonParser alloc] init];
NSError *error = nil;
NSArray *jsonObj = [jsonPar objectWithString:jsonString error:&error];
id jsonObj = [jsonPar objectWithString:jsonString error:&error];
if ([jsonObj isKindOfClass:[NSDictionary class]])
// treat as a dictionary, or reassign to a dictionary ivar
else if ([jsonObj isKindOfClass:[NSArray class]])
// treat as an array or reassign to an array ivar.
Then get the value :
NSMutableArrary *userMutArr = [NSMutableArray array];
for (NSDictionary *dict in jsonObj)
{
User *userObj = [[[User alloc] init] autorelease];
[userObj setFirstName:[dict objectForKey:#"firstName"]];
[userObj setLastName:[dict objectForKey:#"lastName"]];
[userObj setAge:[[dict objectForKey:#"age"] intValue]];
[userObj setAddress:[dict objectForKey:#"address"]];
[userObj setPhoneNumbers:[dict objectForKey:#"phoneNumber"]];
[userMutArr addObject:userObj];
}
Hope you will understand. and read some Documents. it will help you.

It looks like you are in need of JSON Parsing. Here, what you want is JSON Parsing, not separating data from the JSON Response. JSON is the format of the data in which data is formatted in Key-Value pairs. You can fetch the "Value" of any object using the "Key".
Your first two lines are correct.
NSURL *url = [NSURL URLWithString:strUrl];
NSData *respData = [NSData dataWithContentsOfURL:url];
Now, you can parse JSON Response like this :
NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:respData options:kNilOptions error:&error];
NSString *pSerial = [json objectForKey:#"pserial"];
This will give you the value of "pserial" from your response. Similarly, you can get the values for "success" and "message". You can check it using this line :
NSLog(#"pserial :: %#",pserial);

You need to parse the JSON Response String, you can use any JSON parser like:
https://github.com/stig/json-framework/
And in your code do:
NSString *strResp = [[NSString alloc]initWithData:respData encoding:NSUTF8StringEncoding];
NSDictionary *ResponseDictionary = [strResp JSONValue];
NSString * pSerial = (NSString*)[ResponseDictionary objectForKey:#"pserial"];

Dont separation by ":" just use JSONValue your response is like
// {"success":"true","message":"You have logged in","pserial":"1"}
// with SBJsonParser parse your object like this
NSDictionary *responseJson = [YOUR-OBJECT JSONValue];
Note: dont forget to add Json header file

Its better you use any OpenSource Json Parser
Here is a stack post Comparison of different Json Parser for iOS

Related

How to parse api response on table view?

My json response data formate as :-
[{"0":"1","id":"1","1":"Pradeep","name":"Pradeep","2":null,"sender":null,"3":null,"
So to parse the "name" on table view?
My own implementation is:-
I am new in ios development please help me
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSDictionary *allDataDictionary=[NSJSONSerialization JSONObjectWithData:webData
options:0 error:nil]; // response saved in allDataDictionary
NSDictionary *feed=[allDataDictionary objectForKey:#"feed"]; // feeds entry
NSArray *feedforentry=[feed objectForKey:#"entry"];
for(NSDictionary *diction in feedforentry)
{
NSDictionary *title=[diction objectForKey:#"title"];
NSString *label=[title objectForKey:#"label"];
[array addObject:label];
}
[[self JustConfesstable]reloadData]; // reload table
}
First of all get data in Dictionary and then store what you want in NSArray.. using Keys
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options: NSJSONReadingMutableContainers error: &error];
NSLog(#"%#",json);
NSLog(#"%#",delegate.firstArray);
NSArray * responseArr = json[#"Deviceinfo"];
NSArray * firstarray=[[NSArray alloc]init];
for(NSDictionary * dict in responseArr)
{
[firstarray addObject:[dict valueForKey:#"name"]];
}
first array contains names.. what you want from that json response.
and then pass that data to tablview. what you want to do here you get the array of name data.
You need to use JSON parser. I will recommend: https://github.com/johnezang/JSONKit
With that you can do:
JSONDecoder *jsonKitDecoder = [JSONDecoder decoder];
NSError *error = nil;
id objectFromJson = [jsonKitDecoder objectWithData:data error:&error];

How to Parse this JSON in Objective-C

I'm new in iPhone programming.
I have to parse this data in JSON in Objective-C.
{"success":1,"check":[{"ChkKey":"2","ChkDeb":"Connection 1","ChkSSID":"Netgear-1111","ChkIP":"192.168.2.103","ChkBlk":"0"}]}
I follow the example for parsing data with Json. But this JSON is so different.
It is composed by two Array.
How can i proceed?
Thanks - A.b.
How about trying something like this ...
//JSON string
NSString *jsonString = #"{\"success\":1,\"check\":[{\"ChkKey\":\"2\",\"ChkDeb\":\"Connection 1\",\"ChkSSID\":\"Netgear-1111\",\"ChkIP\":\"192.168.2.103\",\"ChkBlk\":\"0\"}]}";
//Parse JSON string into an NSDictionary
NSError *e = [[NSError alloc] init];
NSDictionary *jsonData = [NSJSONSerialization JSONObjectWithData:[jsonString dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:&e];
//Output the value of success
NSLog(#"Success:%#", [jsonData objectForKey:#"success"]);
//Get data in the check array
NSDictionary *checkData = [[jsonData objectForKey:#"check"] objectAtIndex:0];
//Output the value of ChkSSID
NSLog(#"ChkSSID:%#", [checkData objectForKey:#"ChkSSID"]);

Parse json in objective-c for my iphone app

i have a problem parsing my json data for my iPhone app, I am new to objective-C. I need to parse the json and get the values to proceed. Please help. This is my JSON data:
[{"projId":"5","projName":"AdtvWorld","projImg":"AdtvWorld.png","newFeedCount":"0"},{"projId":"1","projName":"Colabus","projImg":"Colabus.png","newFeedCount":"0"},{"projId":"38","projName":"Colabus Android","projImg":"ColabusIcon.jpg","newFeedCount":"0"},{"projId":"25","projName":"Colabus Internal Development","projImg":"icon.png","newFeedCount":"0"},{"projId":"26","projName":"Email Reply Test","projImg":"","newFeedCount":"0"},{"projId":"7","projName":"PLUS","projImg":"7plusSW.png","newFeedCount":"0"},{"projId":"8","projName":"Stridus Gmail Project","projImg":"scr4.png","newFeedCount":"0"}]
On iOS 5 or later you can use NSJSONSerialization. If you have your JSON data in a string you can do:
NSError *e = nil;
NSData *data = [stringData dataUsingEncoding:NSUTF8StringEncoding];
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData: data options: NSJSONReadingMutableContainers error: &e];
Edit To get a specific value:
NSDictionary *firstObject = [jsonArray objectAtIndex:0];
NSString *projectName = [firstObject objectForKey:#"projName"];
I would recommend using JSONKit library for parsing.
Here's a tutorial on how to use it.
You will basically end up with a dictionary and use objectForKey with your key to retrive the values.
JSONKit
or
NSJSONSerialization(iOS 5.0 or later)
I have had success using SBJson for reading and writing json.
Take a look at the documentation here and get an idea of how to use it.
Essentially, for parsing, you just give the string to the SBJsonParser and it returns a dictionary with an objectForKey function. For example, your code might look something like:
NSDictionary* parsed = [[[SBJsonParser alloc] init] objectWithString: json];
NSString* projId = [parsed objectForKey:#"projId"];
Use SBJson
SBJsonParser *parser = [[SBJsonParser alloc] init];
NSMutableDictionary *dicRes = [parser objectWithString:stringFromServer error:nil];
No need to use third party classes. Objective-c already includes handling JSON.
The class NSJSONSerialization expects an NSData object or reads from a URL. The following was tested with your JSON string:
NSString *json; // contains your example with escaped quotes
NSData *jsonData = [json dataUsingEncoding:NSUTF8StringEncoding];
NSError *error;
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:jsonData
options:NSJSONReadingAllowFragments error:&error]
For more options with NSJSONSerialization see the documentation.

EXC_BAD_ACCESS whilst parsing JSON using SBJSON. Corresponding message states variable json_string is not a CFString

I have the following response from server side:
{"_playLists":[{"name":"Playlist 1","items":[{"name":"Poza 1","target":"http:\/\/myaudi.fr","url":"http:\/\/test.res-novae.fr\/sfrplay\/upload\/image\/pic1_iphone3.jpg","url_thumb":"http:\/\/test.res-novae.fr\/sfrplay\/upload\/thumb\/pic1_iphone3_thumb.jpg"},{"name":"Poza 2","target":"http:\/\/audifrance.fr","url":"http:\/\/test.res-novae.fr\/sfrplay\/upload\/image\/pic2_iphone3.jpg","url_thumb":"http:\/\/test.res-novae.fr\/sfrplay\/upload\/thumb\/pic2_iphone3_thumb.jpg"}]},{"name":"Playlist 2","items":[{"name":"Poza 3","target":"http:\/\/google.ro","url":null,"url_thumb":null}]}]}
And I'm trying to acces this by using:
SBJSON *parser = [[SBJSON alloc] init];
NSString *responseString = [request responseString];
NSString *json_string = [[NSString alloc] initWithData:responseString encoding:NSUTF8StringEncoding];
NSArray *statuses = [parser objectWithString:json_string error:nil];
But I get EXC_BAD_ACCESS at this line
NSString *json_string = [[NSString alloc] initWithData:responseString encoding:NSUTF8StringEncoding];
saying variable json_string is not a CFString.
Can someone help me solve this and tell me how to act further to acces the JSON components?Thank you:)
EDIT:
{
items = (
{
name = "Poza 1";
target = "http://myaudi.fr";
url = "http://test.res-novae.fr/sfrplay/upload/image/pic1_iphone3.jpg";
"url_thumb" = "http://test.res-novae.fr/sfrplay/upload/thumb/pic1_iphone3_thumb.jpg";
},
{
name = "Poza 2";
target = "http://audifrance.fr";
url = "http://test.res-novae.fr/sfrplay/upload/image/pic2_iphone3.jpg";
"url_thumb" = "http://test.res-novae.fr/sfrplay/upload/thumb/pic2_iphone3_thumb.jpg";
}
);
name = "Playlist 1";
},
{
items = (
{
name = "Poza 3";
target = "http://google.ro";
url = "<null>";
"url_thumb" = "<null>";
}
);
name = "Playlist 2";
}
You should use one of the JSON frameworks available out there, i.e. JSONKit or json-framework, which both makes it really easy to convert strings to JSON objects (i.e. an NSDictionary).
If you're using json-framework, you'd only have to do the following (if you've included JSON.h):
NSDictionary *jsonObject = [responseString JSONValue];
There is a issue with your line
NSString *json_string = [[NSString alloc] initWithData:responseString encoding:NSUTF8StringEncoding];
you have declared responseString as NSString *responseString = [request responseString];
and you are giving it as Data while allocating json_string
You do not need this line
NSString *json_string = [[NSString alloc] initWithData:responseString encoding:NSUTF8StringEncoding];
responseString is already a string (and initWithData: expects a NSData object not NSString). Just feed it straight to the parser:
NSArray *statuses = [parser objectWithString:responseString error:nil];
Can someone help me solve this and tell me how to act further to acces
the JSON components?
You now have a nice NSArray of NSDictionary objects representing your JSON data, you can access the first item, represented by
{"name":"Playlist 1","items":[{"name":"Poza 1","target":"http:\/\/myaudi.fr","url":"http:\/\/test.res-novae.fr\/sfrplay\/upload\/image\/pic1_iphone3.jpg","url_thumb":"http:\/\/test.res-novae.fr\/sfrplay\/upload\/thumb\/pic1_iphone3_thumb.jpg"},{"name":"Poza 2","target":"http:\/\/audifrance.fr","url":"http:\/\/test.res-novae.fr\/sfrplay\/upload\/image\/pic2_iphone3.jpg","url_thumb":"http:\/\/test.res-novae.fr\/sfrplay\/upload\/thumb\/pic2_iphone3_thumb.jpg"}]}
by getting the first element in the array
NSDictionary* dict = [statuses objectAtIndex:0];
and the keys in the dictionary should be "name", and "items". The object for "name" will be an NSString and the object for "items" will be an NSArray containing further NSDictionary objects describing each item.

Parsing JSON to get Google Reader Label information

I am trying to make a google reader app. I am able to get the subscription list in JSON format like this:
{"subscriptions":[{"id":"feed/http://aspn.activestate.com/ASPN/Cookbook/Python/index_rss","title":"ActiveState Code: Python recipes","categories":[{"id":"user/014533032765194560dwd0/label/Programming","label":"Programming"}],"sortid":"E6312EFB","firstitemmsec":"1258141669516","htmlUrl":"http://code.activestate.com/recipes/langs/python/"},
I am interested in getting the label value (in the above case "Programming") into an array. Here is my current code:
-(BOOL)parsedSuccess {
SBJsonParser *parser = [[SBJsonParser alloc]init];
if (!receivedData) {
[self getSubscriptionList:GOOGLE_READER_SUBSCRIPTION_LIST];
}
NSMutableString *body = [[NSMutableString alloc]initWithData:receivedData encoding:NSUTF8StringEncoding];
if (body) {
NSArray *feeds = [parser objectWithString:body error:nil];
NSDictionary *results = [body JSONValue];
NSArray *subs = [results valueForKey:#"subscriptions"];
NSString *subTitles;
for (NSDictionary *title in subs){
subTitles = [title objectForKey:#"categories"];
NSLog(#"%#",subTitles);
}
}
return YES;
}
Can someone help me in getting the label values?
[[[[[result valueforkey:#"subscription"]objectatindex:0]valueforkey:#"categories"]objectatindex:intvalue]valueforkey:#"label"];
I just helped to make logic. Be sure to check for spelling mistakes before implementing.