i am getting response from the server in below method:
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData*)data{
NSString * result;
NSMutableData * _responseData = [[NSMutableData alloc]init];
[_responseData appendData:data];
NSDictionary *dataAsString=(NSDictionary*)[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"data in register reponse : %#",dataAsString);
I get this json value on logs:
dataAsString : {"status":"error","message":"MySQL Error: 1062 : Duplicate entry 'raushan#gmail.com' for key 'loginEmail'"}
Now I want to get a particular value from the string ,e.g. for key "status":
like the method below:
Nsstring * result=[dataAsString objectForKey:#"status"];
NSLog(#"result : %#",result);
but I dodn't get the result and my application crashes. I don't know what is wrong with that. I had tried a lots of way but not succeeded.
Please help me out. How can I retrieve value from dataAsString.
Thank you for your precious time.
NSJSONSerialization *json;
NSDictionary *dataJson;
NSError *error;
json=[NSJSONSerialization JSONObjectWithData:_responseData
options:NSJSONReadingMutableLeaves
error:&error];
dataJson=[[NSDictionary alloc]init];
dataJson=(NSDictionary *)json;
NSString * result=[dataJson valueForKey:#"status"];
if you are having more trouble, refer this link and this.
NSDictionary *parsedObject = [NSJSONSerialization JSONObjectWithData:receiveddata options:0 error:&localError];
NSDictionary *result = [dataAsString objectForKey:#"result"];
NSString *statusString = [result objectForKey:#"status"];
Related
NSString *connection = #"http:"(link);
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
NSError *error = nil;
NSURL *url = [NSURL URLWithString:connection];
NSString *json = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:&error];
NSLog(#"\nJSON: %# \n Error: %#", json, error);
if(!error) {
NSData *jsonData = [json dataUsingEncoding:NSUTF8StringEncoding];
NSLog(#"%#",jsonData);
NSMutableArray *jsonDict = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&error];
NSLog(#"JSON: %#", jsonDict);
}
});
The above code returns :
JSON: "{\"value\":[{\"Id\":\" }}
but
NSData is 69746963 735c222c 5c224973 41767469 76655c22 3a5c2231 5c222c
and jsonDict returns (null).
I am confused what may be going on.
Can somebody please help me figure it out.
I am trying to get the JSON data but it returns null.
Thanks
You say the server gave you this:
JSON: "{\"value\":[{\"Id\":\" }}
If I remove the backslashes that were added by the NSLog command, the actual JSON that you received was
{"value":[{"Id":" }}
That isn't valid JSON. That's all there is to it; the server sent you rubbish data, and there is no way to get any information from it. Contact the people creating the server software and ask them to fix the problem.
And you really, really need to distinguish between what an object really contains, and what NSLog prints. NSLog prints the contents of an NSData object by displaying each byte as two hexadecimal digits.
Try one of these (array or dictionary) without converting it into JSON, depending on what u want :
NSString *connection = #"http://(link)";
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
NSDictionary *jsonDict = [NSDictionary dictionaryWithContentsOfURL:[NSURL URLWithString:connection]];
NSArray *jsonArray = [NSArray arrayWithContentsOfURL:[NSURL URLWithString:connection]];
NSLog(#"DICT: %# ARRAY: %#", jsonDict, jsonArray);
});
I haven't tried it, please paste results?
By the look of your NSString response, it starts with { and ends with } which means it is a NSDictionary.
Change :
NSMutableArray *jsonDict = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&error];
to :
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:jsonData options:nil error:&error];
I am new to iOS. I have this JSON data that I needed to parse:
{
"allseries":[
{
"type":"HR",
"title":"Heart Rate",
"xLabel":"Time",
"yLabel":"Beats per Min",
"defaultUnit":"BPM",
"url":"info/info?user=admin%40korrent.com&type=HR",
"size":18,
"firstTs":1406755651,
"lastTs":1406841254
},
{
"type":"TEMP",
"title":"Temperature",
"xLabel":"Time",
"yLabel":"Temperature",
"defaultUnit":"F",
"url":"info/info?user=admin%40korrent.com&type=TEMP",
"size":6,
"firstTs":1406854147,
"lastTs":1406854283
}
],
"status":"OK"
}
So far this is my code:
NSString *dataReceived= [[NSString alloc] initWithData:_responseData encoding:NSUTF8StringEncoding];
NSLog(#"--> async response data (string): %#", dataReceived);
NSData *jsonData = [dataReceived dataUsingEncoding:NSUTF8StringEncoding];
NSError *jsonError;
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:jsonData options:nil error:&jsonError];
NSLog(#"JSON key and value %#", [dict description]);
NSLog(#" %# ", dict[#"allseries"]);
NSString *jsonString=dict[#"allseries"];
if (_programState == 4){
NSLog(#"state is 4");
NSLog(#"%#",jsonString);
NSData *Data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
However, the code throws invalid argument exception for this line:
NSData *Data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
Further more, jsonString seems totally "inoperable". I cannot split it, append strings to it etc. So what's wrong?
// The following two lines are just for logging and otherwise are not needed.
NSString *dataReceived= [[NSString alloc] initWithData:_responseData encoding:NSUTF8StringEncoding];
NSLog(#"--> async response data (string): %#", dataReceived);
// Deserialize the JSON data into a dictionary
NSError *jsonError;
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData: _responseData options:nil error:&jsonError];
NSLog(#"JSON key and value %#", dict);
// Get the array from the dictionary element "allseries".
NSArray *jsonArray = dict[#"allseries"];
NSLog(#"jsonArray: %#", jsonArray);
Here jsonArray is the array of dictionaries for "allseries" from the JSON
What you did is totally, totally wrong.
dict[#allseries] is not an NSString. It is an NSArray with two elements, and both its elements are NSDictionary.
I'm really scratching my head at this one. I'm using the Pocket API to allow users to archive Pocket articles from my app, but whenever I try to do so with the below code I get this error:
Error Domain=PocketSDK Code=400 "Invalid request, please refer to API documentation" UserInfo=0xc17d3b0 {NSLocalizedDescription=Invalid request, please refer to API documentation}
Code:
NSDictionary *arguments = #{#"action": #"archive",
#"item_id": articleID};
[[PocketAPI sharedAPI] callAPIMethod:#"send" withHTTPMethod:PocketAPIHTTPMethodPOST arguments:arguments handler:^(PocketAPI *api, NSString *apiMethod, NSDictionary *response, NSError *error) {
if (!error) {
NSLog(#"Archived article.");
}
}];
Exactly what part of that is incorrect? Am I not POSTing a send method to the API?
EDIT: I even changed it to have #"action" be #"actions" and to supply it the above NSDictionary, and it returns without an error but doesn't affect it on the Pocket website...
EDIT 2: Per the response of Joseph Chen I changed my code to the following:
// Create data to pass to the Pocket API (a JSON array of actions)
NSError *error;
NSArray *actions = #[#{#"action": #"archive",
#"item_id": articleID}];
NSData *actionsAsJSONData = [NSJSONSerialization dataWithJSONObject:actions options:kNilOptions error:&error];
NSString *actionsAsJSONString = [[NSString alloc] initWithData:actionsAsJSONData encoding:NSUTF8StringEncoding];
NSDictionary *arguments = #{#"actions": actionsAsJSONString};
[[PocketAPI sharedAPI] callAPIMethod:#"send" withHTTPMethod:PocketAPIHTTPMethodPOST arguments:arguments handler:^(PocketAPI *api, NSString *apiMethod, NSDictionary *response, NSError *error) {
if (!error) {
NSLog(#"%#", response);
}
else {
NSLog(#"%#", error);
}
}];
Which returns:
action_results" = (
1
);
status = 1;
Yet when I go to the website and log in, the article I "archived" is still staring me in the face, unarchived.
According to the documentation the actions parameter should be a JSON dictionary. So you could either...
Create the JSON dictionary manually:
NSString *jsonString = [NSString stringWithFormat:#"[{\"action\":\"archive\",\"item_id\":\"%#\"}]", articleID]; // articleID is a NSString?
NSDictionary *arguments = #{#"actions": jsonString};
Use NSJSONSerialization:
NSDictionary *actions = #{#"action": #"archive", #"item_id": articleID};
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:actions
options:kNilOptions
error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData
encoding:NSUTF8StringEncoding];
NSDictionary *arguments = #{#"actions": jsonString};
This answer is also a reference.
Here's the code taken (almost) straight from my app:
NSTimeInterval timestamp = [[NSDate date] timeIntervalSince1970];
NSDictionary *arguments = #{#"actions" : #[#{#"action" : #"archive",
#"item_id" : itemId,
#"time" : [NSString stringWithFormat:#"%ld", (long)timestamp]}]};
[self.pocketAPI callAPIMethod:#"send"
withHTTPMethod:PocketAPIHTTPMethodPOST
arguments:arguments
handler:^(PocketAPI *api, NSString *apiMethod, NSDictionary *response, NSError *error)
{
if (!error) {
// OK
} else {
// handle error
}
}];
I want to add value to a response. But the response is in this format
{
"participants": [
{
"lat_long": "0.0,0.0",
"name": "alma"
}
],
"lat_long": "0.0,0.0",
"_id": "52a80a5dccb8137326000027"
}
How can I add values to the keys name & lat_long. I am using Sbjson method.
Thanks in advance.
NSURL * url=[NSURL URLWithString:#"Give your URL Here"];
NSData * data=[NSData dataWithContentsOfURL:url];
NSError * error;
NSMutableDictionary * jsonDic=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&error];
NSLog(#"%#",jsonDic);
NSMutableArray * jsonArray=jsonDic[#"participants"];
NSLog(#"%#",jsonArray);
NSString * str =[jsonArray valueForKey:#"lat_long"];
NSString * str1 =[jsonArray valueForKey:#"name"];
NSLog(#"%#",str);
NSLog(#"%#",str1);
Try this code.
I'm not sure, what you are asking about, but This helps you to get the keys of the Disctionary .
NSDictionary *json = [NSJSONSerialization .....//Parsed JSon
NSMutableDictionary *arrCopy = [json mutableCopy];
NSArray *keys= [json allKeys];
for (NSString *keysV in keys){
NSLog(#"Keys are %#", keysV);
if ([keysV isEqualToString:#"_id"]) {
[arrCopy setValue:#"121213211323" forKey:keysV];
}else if (){
}.......................
}
NSLog(#"After Value added: %#", arrCopy);
I have searched online for solution toward this problem, but the result that is always returned to me is null.
This is the following string that I received from a web. Everything seems to work fine. However, when I were to convert this string into an array then the result returned is null.
The code:
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSLog(#"connectionDidFinishLoading");
NSLog(#"Succeeded! Received %d bytes of data",[self.responseData length]);
// String
NSString *responseString = [[NSString alloc] initWithData:self.responseData encoding:NSUTF8StringEncoding];
NSLog(#"%#", responseString);
NSDictionary *resultsDictionary = [responseString objectFromJSONString];
NSLog(#"%#", resultsDictionary); // Returns null
}
The result:
[{"cid":"382595836","name":"\u514d\u7a0e\u5e97\u4e13\u5356\u54c1"},{"cid":"382595837","name":"\u9650\u91cf\u7248\u9999\u6c34"},{"cid":"380837083","name":"\u5973\u58eb\u7cbe\u88c5"},{"cid":"380837082","name":"\u7537\u58eb\u7cbe\u88c5"},{"cid":"61540749","name":"\u7b80\u88c5\u5973\u7528\u9999\u6c34"},{"cid":"24213689","name":"\u7b80\u88c5\u7537\u7528\u9999\u6c34"},{"cid":"25541561","name":"Q\u9999\u5973\u58eb"},{"cid":"25541841","name":"Q\u9999\u7537\u58eb"}]
May anyone provide me a way to think through this.
Thanks.
try this
NSMutableData *responseData; // use in .h class
use this function in use in .m class
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
NSLog(#"connection did receive data");
[responseData appendData:data];
NSString *responseString = [NSString stringWithUTF8String:[responseData bytes]];
NSLog(#"%#",responseString);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(#"Succeeded! Received %d bytes of data", [responseData length]);
}
Use below code. The code will work on ios 5.0 and later.
NSArray* list = [NSJSONSerialization JSONObjectWithData:self.responseData options:kNilOptions
error:&error];
I did this. It's working fine for me. Can you try below one logic.
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"demo" ofType:#"json"];
NSData *myData = [NSData dataWithContentsOfFile:filePath];
NSError *error;
id json = [NSJSONSerialization JSONObjectWithData:myData options:kNilOptions error:&error];
NSArray *list = (NSArray *)json;
The objectFromJSONString will return nil if the string you're passing in isn't valid JSON.
I checked this
[{"cid":"382595836","name":"\u514d\u7a0e\u5e97\u4e13\u5356\u54c1"},{"cid":"382595837","name":"\u9650\u91cf\u7248\u9999\u6c34"},{"cid":"380837083","name":"\u5973\u58eb\u7cbe\u88c5"},{"cid":"380837082","name":"\u7537\u58eb\u7cbe\u88c5"},{"cid":"61540749","name":"\u7b80\u88c5\u5973\u7528\u9999\u6c34"},{"cid":"24213689","name":"\u7b80\u88c5\u7537\u7528\u9999\u6c34"},{"cid":"25541561","name":"Q\u9999\u5973\u58eb"},{"cid":"25541841","name":"Q\u9999\u7537\u58eb"}] 2012-11-30 14:29:52.779 com.JSON.Product[1979:c07]
in JSONLint it shows it is an invalid JSON.