iphone objective-c : string to NSData conversion for json deserialization - iphone

I receive json from a webservice into a NSMutableData.
That gets converted into a NSDictionary using TouchJson.
NSDictionary *dictionary = [[CJSONDeserializer deserializer] deserializeAsDictionary:responseData error:&error];
NSString *strData = [dictionary objectForKey:#"cars"];
I then retrieve a string from a key from that dictionary.
The string looks like below
{
b = "http://schemas.datacontract.org/";
car = (
{
"car_name" = "Honda Civic";
year = 2011;
"dealer" = "local honda dealer";
"bought on" = {
nil = 1;
};
"license_number" = 1234567;
status = ReadyToGo;
}
)};
Essentially there can be 'n' records against the 'car' key.
when I try to convert the above to NSData using
NSData *jsonData = [strData dataUsingEncoding:NSUTF8StringEncoding];
and also
NSData *jsonData = [strData dataUsingEncoding:[NSString defaultCStringEncoding]];
but I get
[__NSCFDictionary dataUsingEncoding:]: unrecognized selector sent to instance 0x532bb70
I have tried a few other encodings available and xcode still threw up.
How can I figure out the encoding being used?
This is my first attempt at deserealizing json in objective-c.
What am I missing/doing wrong here?
Thanks

I think it's not a string at all....
change to this and test....
NSDictionary *dictionary = [[CJSONDeserializer deserializer] deserializeAsDictionary:responseData error:&error];
NSDictionary *carsDictionary = [dictionary objectForKey:#"cars"];
NSArray *arrayOfCarDictionaries = [carsDictionary objectForKey:#"car"];

Related

NSDictionary to NSString JSON

I am trying to wrap my head around pulling a keys value from a JSON array and saving it as a String for comparison later: The following code makes my app crash when it gets to this section of code. I don't understand why.
My json array looks like so:
[{"User_Id":"CRNA000099","User_Name":"jbliz","User_Fname":"Julia"}]
My xcode:
userarray_login = [NSJSONSerialization JSONObjectWithData:dataURL options:kNilOptions error:&error];
NSDictionary* userType = [userarray_login objectForKey:#"User_Name"];
NSString *userPermission = [userType objectAtIndex:0];
if ([userPermission isEqualToString:#"jbliz"])
{
NSLog(#"I should get the avalue here: %#", userPermission);
}
I am confused between NSDictionary and NSString. Any feedback would be a
NSMutableArray *name=[[[NSMutableArray alloc] initWithArray:[userarray_login valueForKey:#"User_Name"]]retain];
// Get the only all Names into name Array from json Array
NSString *userPermission = [name objectAtIndex:0]; // get the first name from Array
if ([userPermission isEqualToString:#"jbliz"])
{
NSLog(#"I should get the avalue here: %#", userPermission);
}
Json Array : [{"User_Id":"CRNA000099","User_Name":"jbliz","User_Fname":"Julia"},{},...] an array contains Dictionaries.
for this try like,
NSArray * userarray_login = [NSJSONSerialization JSONObjectWithData:dataURL options:kNilOptions error:&error];
for (NSDictionary * dict in userarray_login) {
NSString * name = [dict objectForKey:#"User_Name"];
if ([name isEqualToString:#"jbliz"]) {
NSLog(#"Value is here: %#", name);
}
}
Your json has array of Dictionary you need to follow below steps,
//NSJSONSerialization return you array in userarray_login
userarray_login = [NSJSONSerialization JSONObjectWithData:dataURL options:kNilOptions error:&error];
//You fetch Dictionary from the array
NSDictionary* userType = [userarray_login objectAtIndex:0];
//Fetch NSString value using keyValue
NSString *userPermission = [userType objectForKey:#"User_Name"];
//String comparison
if ([userPermission isEqualToString:#"jbliz"])
{
NSLog(#"I should get the avalue here: %#", userPermission);
}
This is correct code for your stuff.

help me to get each elements from my json feed ? Please

I have this JSON data:
{
"data":{
"mat_149":{
"id":"149",
"title":"The closing of 40% profit within 9 month",
"teaser":"profit within 9 months only which is equal to 52% annual profit",
"body":" The auction was presented in a very high and commercial lands.\u000d\u000a",
"files":{
"911":{
"fid":"911",
"filename":"22.JPG",
"filepath":"http://mysite/files/22_0.JPG"
}
}
},
"mat_147":{
"id":"147",
"title":"Company launches the city ",
"teaser":"demands for distinguished lands.",
"body":" The area size is quare meters This is evident through projects and many other projects.\u000d\u000a\u000d\u000a",
"files":{
"906":{
"fid":"906",
"filename":"2D7z.jpg",
"filepath":"http://mysite/dlr/files/2D7Z.jpg"
}
}
},
"mat_link":"mysite.com/"
}
}
I'm parsing it like this with the json-framework:
NSString *response = [[NSString alloc] initWithData:receivedData encoding:NSASCIIStringEncoding] ;
SBJSON *parser = [[SBJSON alloc] init];
NSDictionary *data = (NSDictionary *) [parser objectWithString:response error:nil];
NSLog(#"Data : %#", [data valueForKey:#"data"] );
I am getting Data:
NSLog(#"Data : %#", [data objectForKey:#"data"] );
I am getting the data , but what i should do to get the 'file' items like 'fid' , 'filename' , 'filepath' .How can i get each elements from 'Data' n 'files' and store into some NSStrings ........
Can someone point out what I have to do ? Please
They're all sub-dictionaries aren't they,
just try logging the whole dictionary so go:
NSLog(#"%#", data);
Then you can see the structure.
To get all the other data, you're going to need to create a data model to hold it all, which knows which keys to call to get the specific strings.
Or you could call [data allKeys];
Iterating through that, getting dictionaries that you have the model object for.
E.g:
//Somewhere you declare this
NSArray *keys = [data allKeys]
for (NSString *key in [data allKeys]) {
NSDictionary *oneObject = [dictionary objectForKey:key];
MyObjectModel *object = [[MyObjectModel alloc] init];
object.id = [oneObject objectForKey:#"id"];
object.title = [oneObject objectForKey:#"title"];
//etc
//then you create another dict for files
}
Alex

SBJsonParser in iPhone app

I'm working with JSON library and see this situation:
Convert JSON string to NSDictionary
Scenario 1:
NSString *jsonString = #"{\"Name\":\"Foo\", Points:5}";
NSDictionary *dictionary = (NSDictionary*)[jsonParser objectWithString:jsonString];
NSLog(#"Dictionary: %#",dictionary);
I see the result as followed:
Dictionary: {
Name = "Foo";
Points = 5;
}
So that's correct.
Scenario 2:
NSString *jsonString = #"{\"Name\":\"Foo\", Points:0.5}";
NSDictionary *dictionary = (NSDictionary*)[jsonParser objectWithString:jsonString];
NSLog(#"Dictionary: %#",dictionary);
I see the result as followed:
Dictionary: {
Name = "Foo";
Points = "0.5";
}
???
Scenario 3:
NSString *jsonString = #"{\"Name\":\"Foo\", Points:-1}";
NSDictionary *dictionary = (NSDictionary*)[jsonParser objectWithString:jsonString];
NSLog(#"Dictionary: %#",dictionary);
I see the result as followed:
Dictionary: {
Name = "Foo";
Points = "-1";
}
???
Why does the JSON library convert the negative numbers or number less than 1 into string?
Do you know how to prevent this from happening?
I do not have the "why", but it may not be an issue for you since you can call for the intValue or floatValue when retrieving.
NSLog(#"Points = %.2f", [[dictionary valueForKey:#"Points"] floatValue]);

key values from an NSDictionary formatting with "()"

I'm trying to pull two values from this Dictionary, But the values I'm getting have "()" around them. Any Ideas what is causing this?
Here is the ServerOutput:
{"Rows":[{"userid":"1","location":"beach"}]}
Dictionary after JSON:
{
Rows = (
{
location = beach;
userid = 1;
}
);
}
This is what I'm getting:
location : (
beach
)
user Id : (
1
)
Both the userid and the location key values have the "()". Here is the code. Thanks a lot.
NSString *serverOutput= [[NSString alloc] initWithData:dataURL encoding:NSUTF8StringEncoding];
if(serverOutput > 1){
SBJSON *jsonFF = [[SBJSON new] autorelease];
NSError *error3 = nil;
NSDictionary *useridDict= [jsonFF objectWithString:serverOutput error:&error3];
NSLog(#"useridDict: %#",useridDict);
idreturn = [[useridDict valueForKey:#"Rows"] valueForKey:#"userid"];
locationreturn = [[useridDict valueForKey:#"Rows"] valueForKey:#"location"];
NSLog(#" user Id : %#", idreturn);
NSLog(#" location : %#", locationreturn);
Just to clarify what is going on. When parsing JSON {} gets returned as a dictionary and [] gets retured as an array. So we have useridDict an NSDictionary containing the parsed data.
'useridDict' has one key Rows which returns an NSArray.
NSArray *useridArray = [useridDict objectForKey:#"Rows"];
Our useridArray has one element, an NSDictionary
NSDictionary *dict = [useridArray objectAtIndex:0];
This dict contains the two keys: location and userid
NSString *location = [dict objectForKey:#"location"];
NSInteger userid = [[dict objectForKey:#"userid"] intValue];
You can use like this.
idreturn = [[[useridDict valueForKey:#"Rows"] objectAtIndex:0]valueForKey:#"userid"];
locationreturn = [[[useridDict valueForKey:#"Rows"] objectAtIndex:0] valueForKey:#"location"];

How to get key value from NSdictonary - iphone sdk

I use an API which provides me data from the web. The data is in JSON format, and is stored in a NSDictionary. Like this:
SBJSON *parser = [[SBJSON alloc] init];
dict = [[NSDictionary alloc]init];
dict = [parser objectWithString:jsonArray error:nil];
Ggb console result for: po dict
1262 = {
"feed_name" = name1;
"new_results" = 6;
"next_update" = "2010-02-16T15:22:11+01:00";
};
1993 = {
"feed_name" = name2;
"new_results" = 0;
"next_update" = "2010-02-16T09:09:00+01:00";
};
How can I access the values "1262" and "1993" and put them in a NSArray, for use in a UITableView?
First of all, SBJSON's objectWithString:error: method will return one of the folowing depending on what the root object is in the JSON message:
NSArray
NSDictionary
So, you shouldn't always assume it'll return you a dictionary unless you know for a fact what will be returned in the JSON.
Secondly, you're allocating a new NSDictionary object, but then assigning the result of the parser to your dict variable, leaking the previously allocated dictionary.
You don't need this line: dict = [[NSDictionary alloc]init];.
Finally, since the returned object is a dictionary, you can get al of the objects out of the dictionary like this:
for (NSString *key in [dict allKeys])
{
NSDictionary *feed = [dict objectForKey:key];
//do stuff with feed.
}
return [dict allKeys];