How to read webservice maked in c# thats retun json - iphone

I need read one webservice that return jsonarry in my iphone application.
After this reading, i will need make load this information in my tableview.
But the return is one string, how make transform this string in one format that my table view understand.
following example return
{"codUf":28,"descricao":"MG"},{"codUf":29,"descricao":"PR"},{"codUf":19,"descricao":"RJ"},{"codUf":25,"descricao":"SP"}]
Thanks !!

If you're using ios5, following the tutorial:
#define kBgQueue dispatch_get_global_queue(
DISPATCH_QUEUE_PRIORITY_DEFAULT, 0) //1
dispatch_async(kBgQueue, ^{
NSData* data = [NSData dataWithContentsOfURL:
kLatestKivaLoansURL];
[self performSelectorOnMainThread:#selector(fetchedData:)
withObject:data waitUntilDone:YES];
});
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:responseData //1
options:kNilOptions
error:&error];
Now your JSON data should be in the json dictionary. Good luck and if you have further problems, do leave a comment.

Related

iOS - How to print value in textfield using delegate

I am new to iOS. I have some problem do you have some solution for it? I am not able to print the json value in textfield
This is my contactViewController.m file:
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
fname.text=#"Hello";
}
After the view is loaded hello value is shown in the text box, but when I call list button to get the json values:
-(IBAction)list:(id)sender{
vedant=[[WebserviceViewController alloc]init];
[vedant listContacts];
}
Then from webserviceViewController.m I pass the jsonResponse to the same file i.e contactViewController.m and parse the json value and print it but it does not shows the value in text field
-(void)allContacts:(NSString *)JSONResponse{
NSLog(#"%#",JSONResponse);
NSData *jsonData = [JSONResponse dataUsingEncoding:NSASCIIStringEncoding];
//
NSError *err;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&err];
int accCount =[json count];
for(int i=0;i<accCount;i++){
NSData *jsonData = [JSONResponse dataUsingEncoding:NSASCIIStringEncoding];
//
// NSLog(#"%#",JSONResponse);
NSError *err;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&err];
NSString *firstName = [NSString stringWithFormat:#"%#", [[json objectAtIndex:i] objectForKey:#"first_name"]];
NSLog(#"%#",firstName); //this prints the actual first name in console But
fname.text=firstName;
NSLog(#"%#",fname.text); //it prints "(Null)" in console
}
}
Do I need to create delegate to pass value?
Yes, then any help of creating such delegate some article or example.
Check if fname isn't nil. If you forgot to properly connect it in Interface Builder, fname will be nil and all messages sent to it (like setText:) will be ignored.
Please First check that you have bind your textfield with your fname variable. If yes then try to assign value using this:
fname.text=[NSString stringWithFormat:#"%#",firstName];
Just try this. I hope this will work for you.
Get your first name(i.e value from json) into global value and assign that global value into your textfield . It is so simple. if you still have doubts than reply i'll post sample code
txtName.text=firstname; OR
txtName.text=[NSString stringWithFormat:#"%#",firstName];
Using Delegate i solved this problems
In my contactViewController.m file:
-(IBAction)list:(id)sender{
vedant=[[WebserviceViewController alloc]init];
vedant.delegate=self;
[vedant listContacts];
}
In webserviceViewController.h I created my own delegate
#protocol WebservicesDelegate <NSObject>
-(void)allContacts:(NSString *)JSONResponse;
#end
then in webserviceViewController.m file after getting the json response from backend i am sending the response back to my contactViewController.m file using this code
[self.delegate allContacts:jsonResponse];
the compiler comes back to allContacts function in contactViewController.m file this code is same i didn't change the code now it prints the value.
-(void)allContacts:(NSString *)JSONResponse{
NSLog(#"%#",JSONResponse);
NSData *jsonData = [JSONResponse dataUsingEncoding:NSASCIIStringEncoding];
//
NSError *err;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&err];
int accCount =[json count];
for(int i=0;i<accCount;i++){
NSData *jsonData = [JSONResponse dataUsingEncoding:NSASCIIStringEncoding];
//
// NSLog(#"%#",JSONResponse);
NSError *err;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&err];
NSString *firstName = [NSString stringWithFormat:#"%#", [[json objectAtIndex:i] objectForKey:#"first_name"]];
NSLog(#"%#",firstName); //this prints the actual first name in console But
fname.text=firstName;
NSLog(#"%#",fname.text); //it prints "(Null)" in console
}
}
I think because i was trying to get data from different view and wanted to display the data in another view was the problem.
But by creating the delegate the problem was solves and i can easily send the data from one view to another view.

Download JSON data via NSJSONSerialization

I have a JSON string from PHP's json_encode(). This is how it looks in JSONViewer.stack.hu, and this is how it looks in the browser.
Is it possible to use NSJSONSerialization to download the JSON data directly? If so, I am going to save the downloaded JSON data to SQLite by using FMDB.
id jsonObjectFromUrlString(NSString *urlString)
{
NSURL *url = [NSURL URLWithString:urlString];
NSError *error = nil;
id jsonObject = nil;
NSData *data = [NSData dataWithContentsOfURL:url options:NSDataReadingUncached error:&error];
if(error)
NSLog(#"%#", error);
else
jsonObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
if(error)
NSLog(#"%#", error);
return jsonObject;
}
JSON Serialization method. please refer this.
JSON Serialization
for database did you look at coredata.
please have a look at these ones.
add core data to existing xcode project.
A simple intro to use coreData

NSJSONSerialization not updating data

I am trying to parse JSON with iOS5's NSJSONSerialization. This code CORRECTLY parse the data I wanted for the first time, BUT THEN THE DATA JUST STAYED THE SAME. The JSON on the URL already changed, but the code kept giving me the first data it parsed, which is now incorrect. No matter how many times I "build and run", it keeps giving me the same thing.
When I copied the code to the new project, it works, again, for the first time, and then does the same thing.
I have no idea where the problem is, maybe cache?
Thanks for you help!!!
- (void)fetchedData:(NSData *)responseData {
NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseData
options:kNilOptions
error:&error];
NSArray* allDepartures = [json objectForKey:#"departures"];
NSLog(#"departures: %#", allDepartures);
NSDictionary* stops = [allDepartures objectAtIndex:0];
NSNumber* time = [stops objectForKey:#"expected_mins"];
NSString* name = [stops objectForKey:#"headsign"];
nameLabel.text = [NSString stringWithFormat:#"%#",name];
timeLabel.text = [NSString stringWithFormat:#"%i",[time intValue]];
}
- (IBAction)getInfo:(id)sender {
dispatch_async(kBgQueue, ^{
NSData* data = [NSData dataWithContentsOfURL: myURL];
[self performSelectorOnMainThread:#selector(fetchedData:)
withObject:data waitUntilDone:YES];
});
How do you set "myURL", only in viewDidLoad? After a while if the OS calls viewDidUnload and you run the app again, viewDidLoad is called and myURL is set again. If thats the case you should set myURL every time you call getInfo.

Convert NSData to JSON

I have a NSData object, i need to convert it a NSDictionary object.
NSData *data = ....;
Now i need to convert this to a NSDictionary, How can i do this programatically ?
note: After i save the NSData to the NSDictionary i should be able to access key value pairs of the NSDictionary.
I don't have a code to demonstrate my workings so far, I have only created the NSData object, and have no clue to continue :)
You can subclass MKNetworkOperation and override the responseJSON method with the following:
-(id) responseJSON
{
NSString *rawJSON;
id jsonValue = nil;
if ((rawJSON = [[NSString alloc] initWithData:[self responseData] encoding:NSUTF8StringEncoding]) != nil) {
SBJsonParser *jsonParser = [[SBJsonParser alloc] init];
if ((jsonValue = [jsonParser objectWithString:rawJSON]) == nil) {
NSLog(#"This string doesn't seem to be JSON: '%#'\nraw Data : '%s'", rawJSON, (char *)[[self responseData] bytes]);
return [self responseString];
}
}
else {
NSLog(#"This data doesn't seem to be an UTF8 encoded string: %#", [self responseData]);
return [self responseString];
}
return jsonValue;
}
Please check this link of stack overflow, I have already consumed the JSON services, it will help you a lot. All of the coding is there.
JSON Data Conversion
And here is the tutorial with sample project
JSON Parse Tutorial
Hope you would find it helpful
I highly recommend invoking SBJSON framework, it saved my time for many times, exactly finished my work and easily to use. You don't need to know the details of the conversion algorithm, just download and invoke it.
You might want to download it from here, then follow this tutorial to get your things done.

How to convert XML string to JSON using iPhone sdk

I am implementing a client based application. In that I have an xml string. I need to convert it to JSON format and send to the server. I have no idea on converting this. Can you guys please suggest me any documentation or idea to this?
Step #1: Read XML into NSDictionary: http://troybrant.net/blog/2010/09/simple-xml-to-nsdictionary-converter/
Step #2: Convert NSDictionary into JSON: http://code.google.com/p/json-framework/
As Steve said the two steps are those, I leave you a bit of code, maybe can help you a bit more:
// Don't forget the imports ;)
#import "XMLReader.h"
// You must have a XML string from somewhere
NSString XMLString = yourXML;
// I remove all returns and tabs from the text, after i would be annoying if you don't remove it
XMLString = [XMLString stringByReplacingOccurrencesOfString:#"\r" withString:#""];
XMLString = [XMLString stringByReplacingOccurrencesOfString:#"\t" withString:#""];
// Parse the XML into a dictionary
NSError *parseError = nil;
NSDictionary *xmlDictionary = [XMLReader dictionaryForXMLString:XMLString error:&parseError];
NSError *error;
self.dataParsed = [NSJSONSerialization dataWithJSONObject:xmlDictionary
options: NSJSONWritingPrettyPrinted // Pass 0 if you don't care about the readability of the generated string
error:&error];
// Print the dictionary
NSLog(#"%#", xmlDictionary);