parsing JSON of webservice on objective c array - iphone

I'm developing an iphone app and I have a JSON from web service as below:
[
{
"0":"test_w",
"assignment_title":"test_w",
"1":"2011-11-02 04:02:00",
"assignment_publishing_datetime":"2011-11-02 04:02:00",
"2":"2011-11-02 01:53:00",
"assignment_due_datetime":"2011-11-02 01:53:00",
"3":"course_math.png",
"course_icon":"course_math.png",
"4":null,
"submission_id":null
},
{
"0":"\u062a\u0637\u0628\u064a\u0642 \u0631\u0642\u0645 3",
"assignment_title":"\u062a\u0637\u0628\u064a\u0642 \u0631\u0642\u0645 3",
"1":"2011-08-08 00:00:00",
"assignment_publishing_datetime":"2011-08-08 00:00:00",
"2":"2011-08-25 00:00:00",
"assignment_due_datetime":"2011-08-25 00:00:00",
"3":"course_math.png",
"course_icon":"course_math.png",
"4":null,
"submission_id":null
}
]
also I have a tableview and I need to parser assignment_title only on the tableview cells , also I'm using SBJSON library.
so what is the best way to extract assignment_title and put them on cells?

I find the solution from your answers as below:
I created a method with 2 parameters (json_path , field [that i need to show in tableview cell])
- (NSMutableArray*)JSONPath:(NSString *)path JSONField:(NSString *)field{
SBJSON *parser = [[SBJSON alloc] init];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:path]];
// Perform request and get JSON back as a NSData object
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
// Get JSON as a NSString from NSData response
NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
NSArray *statuses = [parser objectWithString:json_string error:nil];
NSMutableArray * tempMutArray = [[[NSMutableArray alloc] init] autorelease];
int i;
for (i=0; i<[statuses count]; i++) {
[tempMutArray addObject:[[statuses objectAtIndex:i] objectForKey:field]];
}
return [tempMutArray copy];
}
after that i call it in cell as following:
//in viewDidLoad
NSArray * homework = [self JSONPath:#"http://....." JSONField:#"assignment_title"];
//In cellForRowAtIndexPath
cell.textLabel.text = [homework objectAtIndex:indexPath.row];
Thanks to all

If you are doing it through NSJSONSerialization you can get array of assignment_title using this simple method ;)
NSError *error = nil;
NSData *jsonData = [NSData dataWithContentsOfURL:apiURL];
id jsonObjectFound = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
NSArray* assignmentTitles = [jsonObjectFound valueForKey:#"assignment_title"];

If performance matters, you might consider using an ASIHTTPRequest to fetch the json asynchronously, then inside the requestFinished: you might do something like:
- (void)requestFinished:(ASIHTTPRequest *)request
{
// Use when fetching text data
NSString *responseString = [request responseString];
//assuming you created a property instance variable NSArray *myArrAssignmentTitles
NSArray *tempArray = [responseString JSONValue];
//making an array of assignment_title
NSMutableArray *tempMutArray = [[NSMutableArray alloc] init];
int i;
for(i = 0;i < [tempArray count];i++){
[tempMutArray addObject:[[tempArray objectAtIndex:i] objectForKey:#"assignment_title"]];
}
//assign the data to the instance variable NSArray *myArrAssignmentTitles
self.myArrAssignmentTitles = tempMutArray;
//release tempMutArray since the instance variable has it
[tempMutArray release];
//call the reload table
[self.tableView reloadData];//i think this is how to reload the table
}
- (void)requestFailed:(ASIHTTPRequest *)request
{
NSError *error = [request error];
}
So, your myArrAssignmentTitles has all the values assignment_title from json
all you do is just apply the array data for the cell e.g.
cell.textLabel.text = [self.myArrAssignmentTitles objectAtIndex:indexPath.row];
its a long code sorry about that. But, thats works for me xD; it fetches the json asynchronously after that it creates an array of assignment_title hopes it helps.

Related

create a json string from NSArray

In my iPhone aplication I have a list of custom objects. I need to create a json string from them. How I can implement this with SBJSON or iPhone sdk?
NSArray* eventsForUpload = [app.dataService.coreDataHelper fetchInstancesOf:#"Event" where:#"isForUpload" is:[NSNumber numberWithBool:YES]];
SBJsonWriter *writer = [[SBJsonWriter alloc] init];
NSString *actionLinksStr = [writer stringWithObject:eventsForUpload];
and i get empty result.
This process is really simple now, you don't have to use external libraries,
Do it this way, (iOS 5 & above)
NSArray *myArray;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:myArray options:NSJSONWritingPrettyPrinted error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
I love my categories so I do this kind of thing as follows
#implementation NSArray (Extensions)
- (NSString*)json
{
NSString* json = nil;
NSError* error = nil;
NSData *data = [NSJSONSerialization dataWithJSONObject:self options:NSJSONWritingPrettyPrinted error:&error];
json = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
return (error ? nil : json);
}
#end
Although the highest voted answer is valid for an array of dictionaries or other serializable objects, it's not valid for custom objects.
Here is the thing, you'll need to loop through your array and get the dictionary representation of each object and add it to a new array to be serialized.
NSString *offersJSONString = #"";
if(offers)
{
NSMutableArray *offersJSONArray = [NSMutableArray array];
for (Offer *offer in offers)
{
[offersJSONArray addObject:[offer dictionaryRepresentation]];
}
NSData *offersJSONData = [NSJSONSerialization dataWithJSONObject:offersJSONArray options:NSJSONWritingPrettyPrinted error:&error];
offersJSONString = [[NSString alloc] initWithData:offersJSONData encoding:NSUTF8StringEncoding] ;
}
As for the dictionaryRepresentation method in the Offer class:
- (NSDictionary *)dictionaryRepresentation
{
NSMutableDictionary *mutableDict = [NSMutableDictionary dictionary];
[mutableDict setValue:self.title forKey:#"title"];
return [NSDictionary dictionaryWithDictionary:mutableDict];
}
Try like this Swift 2.3
let consArray = [1,2,3,4,5,6]
var jsonString : String = ""
do
{
if let postData : NSData = try NSJSONSerialization.dataWithJSONObject(consArray, options: NSJSONWritingOptions.PrettyPrinted)
{
jsonString = NSString(data: postData, encoding: NSUTF8StringEncoding)! as String
}
}
catch
{
print(error)
}
Try like this,
- (NSString *)JSONRepresentation {
SBJsonWriter *jsonWriter = [SBJsonWriter new];
NSString *json = [jsonWriter stringWithObject:self];
if (!json)
[jsonWriter release];
return json;
}
then call this like,
NSString *jsonString = [array JSONRepresentation];
Hope it will helps you...
I'm a bit late to this party, but you can serialise an array of custom objects by implementing the -proxyForJson method in your custom objects. (Or in a category on your custom objects.)
For an example.

Break String that came from Json

I have a String that I got from a webserver which came in json format, but the string is huge with everything in it. I tried using the NSDICTIONARY but to no success. I was wondering what would be the best approach to break this string and add to different strings and eventually put it all in a class of strings. Thanks for the help! Here is my code:
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]init];
[request setURL:[NSURL URLWithString:#"http://mym2webdesign.com/meiplay/paulsuckedabuffalo/artists.php"]];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil]; //Or async request
returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSError *error=nil;
NSLog(#"HHHHHHHHHHHHHH"); //use this to know how far Im getting
NSLog(returnString); // Look at the console and you can see what the restults are
/*NSDictionary *results = [returnString JSONValue];
NSString *ID = [results objectForKey:#"ID"]; // for example
NSLog(#"ID Number: %#", ID);*/
Here is some of the log i get:
[{"ID":"1","name":"kevin","bio":"kevins bio"},{"ID":"1","name":"kevin","age":"20"},{"ID":"2","name":"Cesar","bio":"Cesar bio"},{"ID":"2","name":"Cesar","age":"19"},{"ID":"3", "name":"Katherine", "bio":"Katherines bio"},{"ID":"3", "name":"Katherine", "age":"22"}]
You are doing it wrong. Its a NSArray of NSDictionaries. So first you need to assign it to NSArray and then loop over it to get each individual NSDictionary. See below.
NSArray *results = [returnString JSONValue];
for(NSDictionary *record in results)
{
NSLog(#"ID: %#", [record objectForKey:#"ID"]);
}
You'll probably be better off just using NSJSONSerialization if your app is targeted for at or over iOS 5.0:
NSArray *JSONArray = [NSJSONSerialization JSONObjectWithData:returnData options:0 error:&error];
You might need to experiment with using NSArray vs. NSDictionary, etc., but this should be an overall simpler solution.
Try this :
NSArray *results = [returnString JSONValue];
for (int i=0; i<[results count];i++) {
NSDictionary *DetailDictonary=[results objectAtIndex:i];
NSString *strid=[DetailDictonary objectForKey:#"ID"];
NSString *strName=[DetailDictonary objectForKey:#"name"];
NSString *strBio=[DetailDictonary objectForKey:#"bio"];
// Or You can set it in Your ClassFile
MyClass *classObj=[[MyClass alloc] init];
classObj.strid=[DetailDictonary objectForKey:#"ID"];
classObj.strName=[DetailDictonary objectForKey:#"name"];
classObj.strBio=[DetailDictonary objectForKey:#"bio"];
[YourMainArray addObject:classObj]; //set YourClass to Array
[classObj release];
}

issue in parsing json and displaying data

i am using the below json method and following code to parse json method and display the data which i need on a label.
i followed this link http://www.touch-code-magazine.com/tutorial-fetch-and-parse-json/ and many other but i am not getting the result what i need.Either it throws exception in below code line or else it displays null value.
NSDictionary* profile = [profileinfo objectAtIndex:0]; //throws exception
can anyone help me what is wrong in the below code and what is missing so tat i get the values i.e, phonenumber,firstname and other data from json method.
//Json Method
{
"createdBy":"superadmin",
"createdOn":"2011-11-15T00:49:06+05:30",
"updatedBy":"superadmin",
"updatedOn":"2011-11-15T00:49:06+05:30",
"contactNumber":"9945614074",
"emailNotification":"true",
"firstName":"resident2",
"lastName":"user5",
"loginId":"jin",
"married":"false",
"message":"",
"preferredLanguage":"ko_KR",
"sex":"0",
"smsNotification":"false",
"status":"ACTIVE",
"subscribedPlans":"Intelligent Concierge",
"userName":"Cisco"
}
//code
- (void)loadData
{
dataWebService = [[NSMutableData data] retain];
NSURLRequest *request = [[NSURLRequest requestWithURL:[NSURL URLWithString:#"URL LINK"]]retain];
[[NSURLConnection alloc]initWithRequest:request delegate:self];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
[connection release];
NSString *responseString = [[NSString alloc] initWithData:dataWebService encoding:NSUTF8StringEncoding];
self.dataWebService = nil;
NSArray* profileinfo = [(NSDictionary*) [responseString JSONValue] objectForKey:#"createdBy"];
[responseString release];
NSDictionary* profile = [profileinfo objectAtIndex:0];
//fetch the data
NSNumber* numb = [profile objectForKey:#"contactNumber"];
NSString* name = [profile objectForKey:#"firstName"];
//set the text to the label
label.numberOfLines = 0;
label.text = [NSString stringWithFormat:#"contactNumber: %# \n \n Name: %# \n \n",
numb,name];
}
The jsonValue is your dictionary.
replace
NSArray* profileinfo = [(NSDictionary*) [responseString JSONValue] objectForKey:#"createdBy"];
and
NSDictionary* profile = [profileinfo objectAtIndex:0];
with
NSDictionary * profile = (NSDictionary*)[responseString JSONValue];
and now use objectForKey to get your values

How to store the parsed JSON data in a singl array

I have parsed JSON data the format of my JSON data is
http://www.krsconnect.no/community/api.html?method=bareListEventsByCategory&appid=620&category-selected=350&counties-selected=Vest-Agder,Aust-Agder
SBJsonParser *parser = [[SBJsonParser alloc] init];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://www.krsconnect.no/community/api.html?method=categories&appid=620&mainonly=true"]];
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
NSDictionary *object = [parser objectWithString:json_string error:nil];
NSArray *results = [parser objectWithString:json_string error:nil];
How about creating a data modal?
#interface book:NSObject {
NSString *catId;
NSString *bookName
}
create properties for these two instance vars.
#end
#implementation book
#synthesize catId,bookName;
- (id)init {
self = [super init];
}
- (id)initWithDictionary:(NSDictionary) dict {
self.catId = [dict valueForKey:#"categoryId"];
self.bookName = [dict valueForKey:#"name"];
}
- (void)dealloc {
[catId release];
[bookName release];
[super dealloc];
}
#end
and use it like this
NSMutableArray *bookArray = [[NSmutableArray alloc] initWithCapacity:0];
NSArray *results = [parser objectWithString:json_string error:nil];
for (int i=0; i<[results count]; i++) {
book *bookObject = [[book alloc] initWithDictionary:[results objectAtIndex:i]];
[bookArray addObject:bookObject];
[bookObject release];
}
I think you can do this by way
Adding dictionary to array.
for (NSDictionary *dict in mydict) {
[myArray addObject:dict];
}
You can do more modification and put the logic to set the values in array according
to key as well.
Hope this may help you.Well I haven't checked it now.But may get you to the solution.
Cheers.....

How to read the JSON value on console in iphone

i have the following json value in console:
{"TokenID":"kuiHigen21","isError":false,"ErrorMessage":"","Result":[{"UserId":"153","FirstName":"Rocky","LastName":"Yadav","Email":"rocky#itg.com","ProfileImage":null,"ThumbnailImage":null,"DeviceInfoId":"12"}],"ErrorCode":900}
this is my server api :#"http://192.168.0.68:91/JourneyMapperAPI?RequestType=Login"
//api takes 5 parameters .
when i post data to server api values are posted to server and i get the above response in json format.
i want to parse the above the JSON value that i get in the response and save in sqlite database.
i am doing this code to parse the above JSON value:
-(void)connectionDidFinishLoadingNSURLConnection *)connection
{
NSString *loginStatus = [[NSString alloc] initWithBytes: [webData mutableBytes] lengthwebData length] encoding:NSUTF8StringEncoding];
NSLog(#"%#",loginStatus);
self.webData = nil;
SBJSON *parser =[[SBJSON alloc]init];
NSURLRequest *request = [NSURLRequest requestWithURLNSURL URLWithString"http://192.168.0.68:91/JourneyMapperAPI?RequestType=Login.json"]];
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
// Get JSON as a NSString from NSData response
NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
//NSDictionary *object = [parser objectWithString:json_string error:nil];
// parse the JSON response into an object
// Here we're using NSArray since we're parsing an array of JSON status objects
NSArray *statuses = [parser objectWithString:json_string error:nil];
for (NSDictionary *status in statuses)
{
// You can retrieve individual values using objectForKey on the status NSDictionary
// This will print the tweet and username to the console
NSLog(#"%# - %#", [status objectForKey"Login"],[status objectForKey"LoginKey"]);
[connection release]; [webData release];
}
You should check out some of the JSON parsers, my personal favourite is json-framework. After you've included one of them in your project, where you've got your JSON response from your server:
// Get JSON as a NSString from NSData response
NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
NSDictionary *result = [json_string JSONValue];
NSArray *statuses = [result objectForKey:#"Result"];
which will return your array of results (where each object in the array is an NSDictionary).
You can save this to a database with the help of a model class, Result
NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
NSDictionary *result = [json_string JSONValue];
NSArray *values = [result objectForKey:#"Result"];
NSMutableArray *results = [[NSMutableArray alloc] init];
for (int index = 0; index<[values count]; index++) {
NSMutableDictionary * value = [values objectAtIndex:index];
Result * result = [[Result alloc] init];
result.UserId = [value objectForKey:#"UserId"];
result. FirstName = [value objectForKey:#"FirstName"];
...
[results addObject:result];
[result release];
}
use the array of results to save it to the database.
for (int index = 0; index<[results count]; index++) {
Result * result = [results objectAtIndex:index];
//save the object variables to database here
}