-[__NSSingleObjectArrayI dataUsingEncoding:] Objective C - ios

My JSON string is
"{\"CommentList\":[{\"SubmittedDate\":\"02/01/2017 06:09:32\",\"SubmittedTime\":\"\",\"UserId\":\"af0e1cda5c0\",\"UserName\":\"NepolionBon\",\"Comments\":\"\",\"Complete_Hour\":\"\",\"Complete_Minute\":\"\"}]}"
I need value of "SubmittedDate" and "Complete_Hour" from it.
When I'm trying to convert this string with
NSData *responseData = [responseString dataUsingEncoding:NSUTF8StringEncoding];
getting an error saying
-[__NSSingleObjectArrayI dataUsingEncoding:]: unrecognized selector sent to instance 0x14decfc0
can anyone help me?

You can use this code to get SubmittedDate and Complete_Hour.
NSString *jsonString = #"{\"CommentList\":[{\"SubmittedDate\":\"02/01/2017 06:09:32\",\"SubmittedTime\":\"\",\"UserId\":\"af0e1cda5c0\",\"UserName\":\"NepolionBon\",\"Comments\":\"\",\"Complete_Hour\":\"\",\"Complete_Minute\":\"\"}]}";
NSData *data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSArray* arrComments = [json objectForKey:#"CommentList"];
for (NSDictionary *dict in arrComments) {
NSLog(#"Submit date :%#",[dict objectForKey:#"SubmittedDate"]);
NSLog(#"Comlplete Hour : %#",[dict objectForKey:#"Complete_Hour"]);
}

Related

Deserialise JSON String in Objective C

I received NSData object data from REST API. That contains JSON data which I want to parse.
{
JsonResult = "[{
\"IsAuth\":\"true\",
\"User\":\"
[
{
\\\"userid\\\":\\\"josephH\\\",
\\\"firstname\\\":\\\"joseph\\\",
\\\"lastname\\\":\\\"Henry\\\",
}
]\"}]"
}
This statement gave me the result as a String like below which I am not able to parse as JSON.
myData = [data valueForKey:#"JsonResult"];
"[{
\"IsAuth\":\"true\",
\"User\":\"
[
{
\\\"userid\\\":\\\"josephH\\\",
\\\"firstname\\\":\\\"joseph\\\",
\\\"lastname\\\":\\\"Henry\\\",
}
]\"}]"
When I try to pass this mydata to JSONSerialization the code crashes.
How do I cast the above string to NSDictionary so that I can parse them and use the values of IsAuth and User.?
Code:
[LDService authenticateUser:Uname.text passwordString:Password.text completeBlock:^(NSData * data){
NSError *error;
NSData *jsonData;
NSString *jsonString = nil;
NSMutableDictionary *jsonDict;
if([NSJSONSerialization isValidJSONObject:data])
{
jsonData = [NSJSONSerialization dataWithJSONObject:data
options:kNilOptions
error:&error];
jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}
NSString *formattedString = [jsonString stringByReplacingOccurrencesOfString:#"\\\"" withString:#"'"];
NSLog(#"Formatted string %#",formattedString);
[jsonDict setObject:formattedString forKey:#"JsonResult"];
NSLog(#"Parsed json %#",jsonDict);
}];
Pass your data as data
NSError *error;
NSString *jsonString = nil;
if([NSJSONSerialization isValidJSONObject:data])
{
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:data
options:kNilOptions
error:&error];
jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}
then replace occurance of #"\\\" with #"'"
NSString *formattedString = [jsonString stringByReplacingOccurrencesOfString:#"\\\"" withString:#"'"];
then use this formattedString.
I have investigates your json file from Json formatter & Validator, there are lots of error in your json file, so first check your file from this validator and this formatter gives you error with description. Re-build your json file, if you still getting any problem then ask.

i Can't convert NSData to NSMutableArray

I want to try to convert NSData to NSDictionary or NSArray but some how i can't do that but whenever try to convert into NSString it will converted and gating data so any one can know what is mistake ,help me below is code for convert
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data
options:0
error:nil];
Below code for convert into NSString
NSString *str = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
But Problem is that When get this type of data it will converted on array
Response:
[["superwoman",0],["sugar",0],["sultan trailer",0],["summer",0],["superman",0],["sunday candy",0],["sublime",0],["summer sixteen",0],["superfruit",0],["sultan songs",0]]
but Whenever gat this type of response it will not converted on array formated because of ,[3 on response
Response:
[["ssundee",0],["selena gomez",0],["sia",0],["sorry beyonce",0],["smosh",0],["sweatshirt jacob
sartorius",0],["skydoesminecraft",0],["secret life of pets
trailer",0,[3]]
try this one
NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseObject
options:kNilOptions
error:&error];
1)You need to take the response in id type variable & check the class of response like below.
2)You also need to check if JSON convertion is successful
NSError * error;
id result = [NSJSONSerialization JSONObjectWithData:data
options:0 error:&error];
if (!error) {
if([id isKindOfClass:[NSDictionary class]]){
//Response is Dictonary
} else if ([id isKindOfClass:[NSArray class]]){
//Response is Array
} else {
//any other format
}
} else {
//Handle error
}

Getting element from NSString

my app get data from a php web service and return a NSString
["first name","last name","adress","test#test","000-000-0000","password","code","0"]
How can i get the second element ?
This is a JSON formatted string which you are getting from your web service.
You must be getting bytes from server. Just replace your variable which have bytes stored with my variable "response data".
Code:
NSError* error;
NSArray* myResultArray = [NSJSONSerialization
JSONObjectWithData:responseData options:kNilOptions error:&error];
You will get an array in variable "myResultArray" and you can get all value by index.
Code:
NSString* first name = [myResultArray objectAtIndex:0];
What you have given here is an array and not a string. May be you could provide more details like the exact response and the code that you are trying here.
To Convert a JSON string to NSDictionary all you need to do is:
NSError *jsonError;
NSData *objectData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:objectData
options:nil
error:&jsonError];
And to NSArray :
NSArray *array = [NSJSONSerialization JSONObjectWithData:objectData options:nil error:&jsonError];
NSString *secondElement = array[1];
That web service doesn't return an NSString. It runs data in some format defined by the service, and you convert it to an NSString. Find out what the format actually is, then convert it appropriately, for example using NSJSONSerialization.
The example string your showed here seems wired. This looks more like a array than string. If this is a NSArray then you can do it like this:
NSArray *data = #[#"first name",#"last name", #"adress", #"test#test", #"000-000-0000", #"password", #"code", #"0"];
NSLog (#"Second component = %#", data[1]);
However, if you anticipate this as NSString then this is how you would handle this:
NSString *test = #"[\"first name\",\"last name\",\"adress\",\"test#test\",\"000-000-0000\",\"password\",\"code\",\"0\"]";
NSLog (#"Second component = %#", [test componentsSeparatedByString:#","][1]);

impossible to parse a url containing "and space in xcode

I'm trying to parse json in a url like:
NSError *error = nil;
NSString *sampleUrl= #"http://xbmc:xbmc#192.168.1.23:8080/jsonrpc?request={\"jsonrpc\":%20\"2.0\",%20\"method\":%20\"VideoLibrary.GetMovies\",%20\"params\":%20{%20\"filter\":%20{\"field\":%20\"playcount\",%20\"operator\":%20\"is\",%20\"value\":%20\"0\"},%20\"limits\":%20{%20\"start\"%20:%200,%20\"end\":%2075%20},%20\"properties\"%20:%20[\"art\",%20\"rating\",%20\"thumbnail\",%20\"playcount\",%20\"file\"],%20\"sort\":%20{%20\"order\":%20\"ascending\",%20\"method\":%20\"label\",%20\"ignorearticle\":%20true%20}%20},%20\"id\":%20\"libMovies\"}";
NSLog(#"%# ",sampleUrl);
NSData *jsonData = [NSData dataWithContentsOfURL:[NSURL URLWithString:sampleUrl]];
id jsonObjects = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
but I get an error saying that:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'data parameter is nil'
When I copy my url in my browser: it works!
but not when I tried with xcode
I tried changing the setting "by 22% and eliminating \ : does not work!
how do I proceed?
thanks
The problem is that the string in sampleUrl is not a well formed URL (see RFC 1738).
It contains various characters that are not allowed in URLs, for example { and ". These character have to be percent-escaped before converting to an NSURL.
Where does your URL string really come from?
here is the result that works wonders:
NSString *urlString = [NSString stringWithFormat:#"http://xbmc:xbmc#192.168.1.23:8080/jsonrpc?request={\"jsonrpc\": \"2.0\", \"method\": \"VideoLibrary.GetMovies\", \"params\": { \"filter\": {\"field\": \"playcount\", \"operator\": \"is\", \"value\": \"0\"}, \"limits\": { \"start\" : 0, \"end\": 75 }, \"properties\" : [\"art\", \"rating\", \"thumbnail\", \"playcount\", \"file\"], \"sort\": { \"order\": \"ascending\", \"method\": \"label\", \"ignorearticle\": true } }, \"id\": \"libMovies\"}"];
NSLog(#"%# ",sampleUrl);
NSString *encodedUrl = [urlString stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
NSURL *url = [[NSURL alloc] initWithString:encodedUrl];
NSData *jsonData = [NSData dataWithContentsOfURL:[NSURL URLWithString:encodedUrl]];
id jsonObjects = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
Thank you to you all for the help;)

iOS 7 NSJSONSerialization

I am trying to develop an app that parses json data. I have the following json :
{
myobject:[
{
id:184,
title: "test title"
}
]
}
I have the following code which im trying to get the title data from this json
NSData *jsonData = [NSData dataWithContentsOfURL:myURL];
NSError *error = nil;
NSDictionary *currentObject = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
if(error)
{
NSLog(#"%#",error);
}
NSDictionary *nar = [currentObject objectForKey:#"myobject"];
NSLog(#"%#",[nar valueForKey:#"title"]);
NSString *curTitle = [nar valueForKey:#"title"];
self.myTitle.text = curTitle;
When I log the title, I can see that the title is indeed coming back. However, when I try to set the myTitle.text I get the following error
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSArrayI length]: unrecognized selector sent to instance 0x15631850
In your json my object field is not a dictionary, but array of dictionaries, so [nar valueForKey:#"title"] will return array of valueForKey for each of elements in that array.
If you're sure about data format you can extract string value from it the following way:
 NSArray *nar = [currentObject objectForKey:#"myobject"];
NSString *curTitle = nar[0][#"title"];
But of course it is better to add some data validation/error handling in production code.
It is crash because Your dictionary contain NSArray, not dictionary.
NSArray *ar = [currentObject objectForKey:#"myobject"];
for(NSDictionary *dict in ar)
{
NSLog(#"%#", [dict objectForKey:#"title"];
)
}
NSString *curTitle = [[ar objectAtIndex:0] objectForKey:#"title"];
self.myTitle.text = curTitle;
You are trying to assign NSArray to self.myTitle.text.
NSData *jsonData = [NSData dataWithContentsOfURL:myURL];
NSError *error = nil;
NSDictionary *currentObject = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
if(error)
{
NSLog(#"%#",error);
}
NSArray *nar = [currentObject objectForKey:#"myobject"];
NSString *title = [[nar objectAtIndex:0] objectForKey:#"title"];
NSLog(#"%#",title);
self.myTitle.text = title;

Resources