I am using php to get json data and here is response.
{"array":[{"Category":{"charity_id":"2","charity_name":"GiveDirectly","charity_amt":"0.20"}}]}
and here is my Objective-c code
NSError *err;
NSURL *url=[NSURL URLWithString:#"url"];
NSURLRequest *req=[NSURLRequest requestWithURL:url];
NSData *data = [NSURLConnection sendSynchronousRequest:req returningResponse:nil error:&err];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:&err];
if ([json isKindOfClass:[NSDictionary class]]){
NSArray *yourStaffDictionaryArray = json[#"array"];
if ([yourStaffDictionaryArray isKindOfClass:[NSArray class]]){
for (NSDictionary *dictionary in yourStaffDictionaryArray) {
for(NSDictionary *dict in dictionary[#"Category"]){
NSLog(#"%#",[[((NSString*)dict) componentsSeparatedByString:#"="] objectAtIndex:0] );
}
}
}
}
But this only returns the name's not the value. I have searched most of the question on this site but nothing helped be. Please help me i am new to iOS.
Thanks
Dictionary output is
{
"charity_amt" = "0.20";
"charity_id" = 2;
"charity_name" = GiveDirectly;
}
You don't need to do ComponentSeparatedByString. Once you get the NSDictionary for #"Category", you can get its value by using its keys.
Something like
if ([json isKindOfClass:[NSDictionary class]]){
NSArray *yourStaffDictionaryArray = json[#"array"];
if ([yourStaffDictionaryArray isKindOfClass:[NSArray class]]){
for (NSDictionary *dictionary in yourStaffDictionaryArray) {
NSDictionary *dict = dictionary[#"Category"];
NSLog(#"%#",dict[#"charity_id"]);
}
}
}
Always Remember that when there are { } curly brackets, it means it is Dictionary and when [ ] this, means Array
NSURL *url=[NSURL URLWithString:#"Your JSON URL"];
NSData *data = [[NSData alloc] initWithContentsOfURL:url];
NSMutableDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
NSArray *array = json[#"array"];
for(NSMutableDictionary *dic in array)
{
NSLog(#"%#",dic[#"Category"][#"charity_id"]); // prints 2
NSLog(#"%#",dic[#"Category"][#"charity_name"]); // GiveDirectly
NSLog(#"%#",dic[#"Category"][#"charity_amt"]); // 0.20
}
this is my parser json data, it's demo
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
NSString *urlString = #"https://api.foursquare.com/v2/venues/search?categoryId=4bf58dd8d48988d1e0931735&client_id=TZM5LRSRF1QKX1M2PK13SLZXRXITT2GNMB1NN34ZE3PVTJKT&client_secret=250PUUO4N5P0ARWUJTN2KHSW5L31ZGFDITAUNFWVB5Q4WJWY&ll=37.33%2C-122.03&v=20140118";
NSURL *url = [NSURL URLWithString:urlString];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
// NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:request
queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
NSString *string = [[NSString alloc] initWithData:data
encoding:NSUTF8StringEncoding];
[self parser:data];
}];
}
- (void)parser:(NSData *)data
{
NSMutableDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data
options:0
error:nil];
[dictionary enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
[obj enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
}];
}];
}
Related
Im loading a database from a website through JSON. When I download the database I use UTF8 to make all characters appear correctly and when I NSLOG them it all appears as it should. But when I analyze the data using JSON and afterwards try to filter out just a few of the words, the words with special characters become like this: "H\U00f6ghastighetst\U00e5g" where it should say: "Höghastighetståg".
I have tried to find a way to make the code convert the text back to UTF8 after filtering but somehow I can't make it happen. Would be really helpful for some answers.
NSError *error;
NSString *url1 = [NSString stringWithContentsOfURL:[NSURL URLWithString:#"http://www.pumba.se/example.json"] encoding:NSUTF8StringEncoding error:&error];
NSLog(#"Before converting to NSData: %#", url1);
NSData *allCoursesData = [url1 dataUsingEncoding:NSUTF8StringEncoding];
NSMutableDictionary *JSONdictionary = [NSJSONSerialization
JSONObjectWithData:allCoursesData
options:kNilOptions
error:&error];
if( error )
{
NSLog(#"%#", [error localizedDescription]);
}
else {
NSMutableArray *allNames = [NSMutableArray array];
NSArray* entries = [JSONdictionary valueForKeyPath:#"hits.hits"];
for (NSDictionary *hit in entries) {
NSArray *versions = hit[#"versions"];
for (NSDictionary *version in versions) {
NSDictionary *properties = version[#"properties"];
NSString *status = [properties[#"Status"] firstObject];
NSString *name = [properties[#"Name"] firstObject];
if ([status isEqualToString:#"usable"]) {
[allNames addObject:name];
}
}
}
NSLog(#"All names: %#", allNames);
}}
try with
+ (NSString *)utf8StringEncoding:(NSString *)message
{
NSString *uniText = [NSString stringWithUTF8String:[message UTF8String]];
NSData *msgData = [uniText dataUsingEncoding:NSNonLossyASCIIStringEncoding];
message = [[NSString alloc] initWithData:msgData encoding:NSUTF8StringEncoding];
return message;
}
or
+ (NSString *)asciiStringEncoding:(NSString *)message
{
const char *jsonString = [message UTF8String];
NSData *jsonData = [NSData dataWithBytes:jsonString length:strlen(jsonString)];
message = [[NSString alloc] initWithData:jsonData encoding:NSNonLossyASCIIStringEncoding];
return message;
}
and this code can help you
+ (NSDictionary *)jsonStringToObject:(NSString *)jsonString
{
NSData *data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *jsonResponse;
if (data)
jsonResponse = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
return jsonResponse;
}
+ (NSString *)objectToJsonString:(NSDictionary *)dict
{
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
if (jsonData.length > 0 && !error)
{
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
return jsonString;
}
return nil;
}
I have dictionary data like this and one array on image.
{ "result":"Successful","data":{"id":"12","product_name":"12\" Round
Plate","sku":"ECOW12RP","description":"Diameter 12 inch x\tDepth 0.9
inch","price":"153.00","business_price":"365.00","image":[{"image":"1454499068ecow12rp_01.jpg"}],"pack_size":"20","business_pack_size":"50","category":"2,3","tax_class":"1","created":"2016-02-03","altered":"2016-02-03
17:52:58","status":"1","deleted":"0","arrange":"1","delivery":"150.00"}}
I want to parse all the key values from it. this is the code which i use for this task.
-(void)viewDidLoad
{
NSLog(#"d %ld", (long)id);
NSString* myNewString = [NSString stringWithFormat:#"%i", id];
NSURL *producturl = [NSURL URLWithString:#"http://dev1.brainpulse.org/ecoware1/webservices/product/" ];
NSURL *url = [NSURL URLWithString:myNewString relativeToURL:producturl];
NSData * imageData = [NSData dataWithContentsOfURL:url];
UIImage * productimage = [UIImage imageWithData:imageData];
NSURL *absURL = [url absoluteURL];
NSLog(#"absURL = %#", absURL);
NSURLRequest *request= [NSURLRequest requestWithURL:absURL];
[NSURLConnection connectionWithRequest:request delegate:self];
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(nonnull NSURLResponse *)response
{
data = [[NSMutableData alloc] init];
NSLog(#"Did receive response");
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)thedata
{
[data appendData:thedata];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
NSDictionary *dictionary = [[NSJSONSerialization JSONObjectWithData:data options:0 error:nil]objectForKey:#"data"];
NSLog(#"arr %#", dictionary);
[productdetail removeAllObjects];
for (NSString *tmp in dictionary)
NSMutableDictionary *temp = [NSMutableDictionary new];
[temp setObject:#"product_name" forKey:#"product_name"];
//[temp setObject:[tmp objectForKey:#"id"] forKey:#"id"];
// [temp setObject:[tmp objectForKey:#"image"] forKey:#"image"];
[productdetail addObject:temp];
NSLog(#"detail %#", productdetail);
}
I tried to parse string from nsdictionary with the help of for loop, but I get product details array null, i don't know why it not get key value.
i am parse data which is in nsdictionary but i have null array when i try to parse image array in this json data please look at this json data.
{"result":"Successful","data":{"id":"2","product_name":"6\" Round Plate","sku":"ECOW6RP","description":"Diameter 6.0 (inch) x Depth 0.6 (inch)\r\n\r\nPerfect for finger foods!","price":"42.89","business_price":"100.00","image":[{"image":"1454499251ecow6rp_01.jpg"}],"pack_size":"20","business_pack_size":"50","category":"2,3","tax_class":"1","created":"2016-01-19","altered":"2016-02-06 16:06:10","status":"1","deleted":"0","arrange":"1","delivery":"150.00"}}
try this
Option-1
NSDictionary *dictionary = [[NSJSONSerialization JSONObjectWithData:data options:0 error:nil]objectForKey:#"data"];
[productdetail removeAllObjects];
if (dictionary)
{
NSMutableDictionary *temp = [NSMutableDictionary new];
[temp setObject:[dictionary objectForKey:#"product_name"] forKey:#"product_name"];
[productdetail addObject:temp];
}
Regarding your specific question to get the product_name data into your dictionary, this will work
NSDictionary *dictionary = [[NSJSONSerialization JSONObjectWithData:data options:0 error:nil]objectForKey:#"data"];
NSMutableDictionary *temp = [NSMutableDictionary new];
if ([dictionary objectForKey:#"product_name"]){
[temp setObject:[dictionary objectForKey:#"product_name"] forKey:#"product_name"];
}
If you print out the dictionary you made, you should see it is in there.
NSLog(#"the temp dictionary value for ProductName: %#", [temp objectForKey:#"product_name"];
I'm using the camfind api, I post a request where I send the api an image and get a token, and then I can use the token to get what the image is, but this takes two steps, a post and a get request. I want to combine them, so the get request auto fires right when the server responds to the post request. Here is the code :
I specify a value for the token at the top
NSString *tokenValue;
the request method, here an image is selected and sent to the server, the server sends a token response back in this request
- (void *) requestMethod: (UIImage *)imageToConvert{
NSString *temp = #"saved";
NSLog(#"%#", temp);
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDirectoryPath = [paths objectAtIndex:0];
NSString *imagePath = [documentDirectoryPath stringByAppendingPathComponent:#"tmp_image.jpg"];
NSURL *imageURL = [NSURL fileURLWithPath:imagePath];
NSData *imageData = UIImageJPEGRepresentation(imageToConvert , 1.0);
[imageData writeToURL:imageURL atomically:YES];
// NSString *base64image = [NSString stringWithFormat:#"%#",[imageData base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength]];
NSString *base64image = [imageData base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
// These code snippets use an open-source library.
// NSString *baseboy = [base64image stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
// NSURL *urlimage_request = [NSURL URLWithString:[base64image stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSDictionary *headers = #{#"X-Mashape-Key": #"********"};
NSDictionary *parameters = #{#"focus[x]": #"480", #"focus[y]": #"640", #"image_request[altitude]": #"27.912109375", #"image_request[image]": imageURL, #"image_request[language]": #"en", #"image_request[latitude]": #"35.8714220766008", #"image_request[locale]": #"en_US", #"image_request[longitude]": #"14.3583203002251"};
UNIUrlConnection *asyncConnection = [[UNIRest post:^(UNISimpleRequest *request) {
[request setUrl:#"https://camfind.p.mashape.com/image_requests"];
[request setHeaders:headers];
[request setParameters:parameters];
}] asJsonAsync:^(UNIHTTPJsonResponse *response, NSError *error) {
NSInteger code = response.code;
NSDictionary *responseHeaders = response.headers;
UNIJsonNode *body = response.body;
NSData *rawBody = response.rawBody;
NSString *token = response.description;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:response.rawBody
options:kNilOptions
error:nil];
NSLog(#"Response status: %ld\n%#", (long) response.code, json);
for(NSString *key in [json allValues])
{
tokenValue = [json valueForKey: #"token" ];
NSString *two = [json valueForKey: #"token" ]; // assuming the value is indeed a string
NSLog(#"Token :%#", two);
NSString *one = #"https://camfind.p.mashape.com/image_responses" ;
NSDictionary *headers = #{#"X-Mashape-Key": #"9hcyYCUJEsmsh4lNTgpgVX1xRq0Ip1uogovjsn5Mte0ONVBtes", #"Accept": #"application/json"};
NSString *responseString = [NSString stringWithFormat:#"%#/%#", one, two];
// NSString *responseURL = [one stringByAppendingString:two];
NSLog(#"response URL %#", responseString);
// UNIUrlConnection *asyncConnection = [[UNIRest get:^(UNISimpleRequest *request) {
// [request setUrl:responseString];
// [request setHeaders:headers];
// }] asJsonAsync:^(UNIHTTPJsonResponse *response, NSError *error) {
// NSInteger code = response.code;
// NSDictionary *responseHeaders = response.headers;
// UNIJsonNode *body = response.body;
// NSData *rawBody = response.rawBody;
// NSDictionary *json = [NSJSONSerialization JSONObjectWithData:response.rawBody
// options:kNilOptions
// error:nil];
// NSLog(#"Response status: %ld\n%#", (long) response.code, json);
//
//
// // NSLog(#"didfinishLoadingbody%#",rawBody);
// // NSLog(#"didfinishLoadingbody%#",body);
// //
// // NSLog(#"didfinishLoading responseheader%#",responseHeaders);
// // NSLog(#"didfinishLoading tok%#",token);
// }];
}
// NSLog(#"didfinishLoadingbody%#",rawBody);
// NSLog(#"didfinishLoadingbody%#",body);
//
// NSLog(#"didfinishLoading responseheader%#",responseHeaders);
// NSLog(#"didfinishLoading tok%#",token);
}];
return (__bridge void *)(self);
}
the response method below uses the token from the request above to print out what the image is
- (void *) responseMethod {
// These code snippets use an open-source library.
NSString *one = #"https://camfind.p.mashape.com/image_responses" ;
NSString *responseString = [NSString stringWithFormat:#"%#/%#", one, tokenValue];
NSDictionary *headers = #{#"X-Mashape-Key": #"9hcyYCUJEsmsh4lNTgpgVX1xRq0Ip1uogovjsn5Mte0ONVBtes", #"Accept": #"application/json"};
UNIUrlConnection *asyncConnection = [[UNIRest get:^(UNISimpleRequest *request) {
[request setUrl:responseString];
[request setHeaders:headers];
}] asJsonAsync:^(UNIHTTPJsonResponse *response, NSError *error) {
NSInteger code = response.code;
NSDictionary *responseHeaders = response.headers;
UNIJsonNode *body = response.body;
NSData *rawBody = response.rawBody;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:response.rawBody
options:kNilOptions
error:nil];
NSLog(#"Response status: %ld\n%#", (long) response.code, json);
// NSLog(#"didfinishLoadingbody%#",rawBody);
// NSLog(#"didfinishLoadingbody%#",body);
//
NSLog(#"didfinishLoading responseheader%#",responseHeaders);
// NSLog(#"didfinishLoading tok%#",token);
}];
return (__bridge void *)(self);
}
rest of the vc other stuff
-(void)loadView {
[super loadView];
}
- (void)viewDidLoad{
[super viewDidLoad];
}
-(void)viewDidAppear:(BOOL)animated{
[super viewDidAppear:animated];
}
-(void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
-(void)viewWillDisappear:(BOOL)animated{
[super viewWillDisappear:animated];
}
I don't know how to make the response method fire right away when the server replies, I don't know objc, im using this in a swift project
#end
This question already has an answer here:
Parsing JSON response .
(1 answer)
Closed 8 years ago.
Hai I need to get the id & status from the service for login my code is below. please guide me to get the values.. Thanks in advance..
NSString *Username= txtUsername.text;
NSString *Password=txtPassword.text;
NSString *link = [NSString stringWithFormat:#"http://www.xxx/login.php?user=%#&pass=%#&format=json",Username,Password];
NSURL *url=[NSURL URLWithString:link];
NSData *data=[NSData dataWithContentsOfURL:url];
1st Do the jSon parsing and then get the particular value from the
key .
Before getting any value , we have to understand the tree of jSon.
Here "posts" is an NSArray ,within that one DIctionary "post" is
there ,which again contains another dictionary.
Below is the complete code.
(void)viewDidLoad
{
[super viewDidLoad];
NSString *Username= txtUsername.text;
NSString *Password=txtPassword.text;
NSString *link =
[NSString stringWithFormat:#"http://www.some.com/webservice/login.php?user=%#&pass=%#&format=json",Username,Password];
dispatch_async(kBgQueue, ^{
NSData* data = [NSData dataWithContentsOfURL:
kLatestKivaLoansURL];
[self performSelectorOnMainThread:#selector(fetchedData:)
withObject:data waitUntilDone:YES];
}); }
Then call that selector fetchedData
(void)fetchedData:(NSData *)responseData {
//parse out the json data
NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseData
options:kNilOptions
error:&error];
if(!error){
NSArray* postArray = [json objectForKey:#“posts”]; //This is an array
if (postArray.count>0) {
NSDictionary *dict = [[postArray objectAtIndex:0] objectForKey:#"post" ];
NSString *id_ = [dict objectForKey:#"id"];
NSString *status_ = [dict objectForKey:#"status"];
}
}
}
Can you post your json string. You can use NSJSONSERIALISATION to convert data (json string ) into NSDictionary. Then use the keys to extract the values. I'm replying through mobile so I can't write the actual code.
Use Below code to parse Json in IOS
NSString *Username= txtUsername.text;
NSString *Password=txtPassword.text;
NSString *link = [NSString stringWithFormat:#"http://www.some.com/_webservice/login.php?user=%#&pass=%#&format=json",Username,Password];
NSURL *url=[NSURL URLWithString:link];
NSMutableURLRequest *req1 = [NSMutableURLRequest requestWithURL:url];
NSURLResponse *response;
NSError *error;
//getting the data
NSData *newData = [NSURLConnection sendSynchronousRequest:req1 returningResponse:&response error:&error];
NSString *responseString = [[NSString alloc] initWithData:newData encoding:NSUTF8StringEncoding];
NSLog(#"basavaraj \n\n\n %# \n\n\n",responseString);
NSData* data = [responseString dataUsingEncoding:NSUTF8StringEncoding];
NSError *myError = nil;
NSDictionary *res = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&myError];
NSString *id=[res objectForKey:#"ID"];
NSString *status=[res objectForKey:#"Status"];
and if u need extra info please go through below link it may help you
Click here for more details
I get the data from an XML file and I am storing it in NSData object. I want to convert that NSData into an NSDictionary and store that data in a plist.
My code is as follows:
NSURL *url = [NSURL URLWithString:#"http://www.fubar.com/sample.xml"];
NSData *data = [NSData dataWithContentsOfURL:url];
NSLog(#"%#", data);
To convert the data, I am using:
- (NSDictionary *)downloadPlist:(NSString *)url {
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:10];
NSURLResponse *resp = nil;
NSError *err = nil;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&resp error:&err];
if (!err) {
NSString *errorDescription = nil;
NSPropertyListFormat format;
NSDictionary *samplePlist = [NSPropertyListSerialization propertyListFromData:responseData mutabilityOption:NSPropertyListImmutable format:&format errorDescription:&errorDescription];
if (!errorDescription)
return samplePlist;
[errorDescription release];
}
return nil;
}
Can anyone please tell me how to do that?
or this:
NSString* dataStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
SBJSON *jsonParser = [SBJSON new];
NSDictionary* result = (NSDictionary*)[jsonParser objectWithString:dataStr error:nil];
[jsonParser release];
[dataStr release];
Try this code:
NSString *newStr1 = [[NSString alloc] initWithData:theData1 encoding:NSUTF8StringEncoding];
NSString *newStr2 = [[NSString alloc] initWithData:theData2 encoding:NSUTF8StringEncoding];
NSString *newStr3 = [[NSString alloc] initWithData:theData3 encoding:NSUTF8StringEncoding];
NSArray *keys = [NSArray arrayWithObjects:#"key1", #"key2", #"key3", nil];
NSArray *objects = [NSArray arrayWithObjects:newStr1 , newStr2 , newStr3 , nil];
NSDictionary *dictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
for (id key in dictionary) {
NSLog(#"key: %#, value: %#", key, [dictionary objectForKey:key]);
}
NSString *path = [[NSBundle mainBundle] pathForResource:#"Login" ofType:#"plist"];
[dictionary writeToFile:path atomically:YES];
//here Login is the plist name.
Happy coding