JSONKit: changing and serializing JSON attribute's value - iphone

I am using JSONKit to parse JSON string into NSDictionary:
NSDictionary *deserializedData = [jsonString objectFromJSONString];
My question is: how can I change the dictionary values and get a changed JSON String?
I've tried to change the dictionary values:
[deserializedData setObject:[NSNumber numberWithInt:iRatings] forKey:#"ratings"];
But the app crashes in that line. What am I doing wrong?
Thanks in advance!

While the other answers are correct, what you really want in this case is:
NSMutableDictionary *deserializedData = [jsonString mutableObjectFromJSONString];
The mutableObjectFromJSONString method will create a mutable dictionary directly, which saves time and memory.

NSDictionary is an immutable dictionary, you need NSMutableDictionary to change the data. I'm not sure about JSONKit, but the built-in Cocoa JSON parser has a flag to return the data in mutable containers.
In worst case, you can do something like that:
NSMutableDictionary* data = [NSMutableDictionary dictionaryWithDictionary:[jsonString objectFromJSONString]];
[data setObject:[NSNumber numberWithInt:iRatings] forKey:#"ratings"];

//
// we begin with our string in json format
//
NSString *jsonString = [[NSString alloc] initWithString:#"{\"1\":\"Hole 1: Rossy Robinson - $25\",\"2\":\"Hole 7: Davey Ambrose - $25\",\"3\":\"Hole 14: Ross Robinson - $25\"}"];
//
// convert the json string to an NSMutableDictionary
//
NSError *e;
NSMutableDictionary *JSONdic = [NSJSONSerialization JSONObjectWithData: [jsonString dataUsingEncoding: NSUTF8StringEncoding] options: NSJSONReadingMutableContainers error: &e];
//
// change a value and add a new value in the dict
//
NSLog(#"before: object for key 1 is: %#", [JSONdic objectForKey:#"1"]);
[JSONdic setObject:#"xxx" forKey:#"1"];
[JSONdic setObject:#"Phil McQuitty" forKey:#"2"];
//
//convert dictionary object to json data
//
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:JSONdic options:NSJSONWritingPrettyPrinted error:&e];
//
// convert the json data back to a string
//
NSString *jsonText = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];\
//
// print out the final results
//
NSLog(#"back to string: %#", jsonText);

You try to change an immutableobject.
NSMutableDictionary *deserializedData = [NSMutableDictionary dictionaryWithDictionary: [jsonString objectFromJSONString]];
This is a mutable dictionary and you can change the values in it.

You try like this:
NSMutableDictionary *deserializedData = [NSMutableDictionary dictionaryWithDictionary: [jsonString objectFromJSONString]];
and then change the values:
[deserializedData setObject:[NSNumber numberWithInt:iRatings] forKey:#"ratings"];
For NSDictionary we cannot add or change values, thats why application is crashing.

Related

How to parse api response on table view?

My json response data formate as :-
[{"0":"1","id":"1","1":"Pradeep","name":"Pradeep","2":null,"sender":null,"3":null,"
So to parse the "name" on table view?
My own implementation is:-
I am new in ios development please help me
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSDictionary *allDataDictionary=[NSJSONSerialization JSONObjectWithData:webData
options:0 error:nil]; // response saved in allDataDictionary
NSDictionary *feed=[allDataDictionary objectForKey:#"feed"]; // feeds entry
NSArray *feedforentry=[feed objectForKey:#"entry"];
for(NSDictionary *diction in feedforentry)
{
NSDictionary *title=[diction objectForKey:#"title"];
NSString *label=[title objectForKey:#"label"];
[array addObject:label];
}
[[self JustConfesstable]reloadData]; // reload table
}
First of all get data in Dictionary and then store what you want in NSArray.. using Keys
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options: NSJSONReadingMutableContainers error: &error];
NSLog(#"%#",json);
NSLog(#"%#",delegate.firstArray);
NSArray * responseArr = json[#"Deviceinfo"];
NSArray * firstarray=[[NSArray alloc]init];
for(NSDictionary * dict in responseArr)
{
[firstarray addObject:[dict valueForKey:#"name"]];
}
first array contains names.. what you want from that json response.
and then pass that data to tablview. what you want to do here you get the array of name data.
You need to use JSON parser. I will recommend: https://github.com/johnezang/JSONKit
With that you can do:
JSONDecoder *jsonKitDecoder = [JSONDecoder decoder];
NSError *error = nil;
id objectFromJson = [jsonKitDecoder objectWithData:data error:&error];

How to separate JSON response in iphone

I have an application in which I am having a json response like this.
{"success":"true","message":"You have logged in","pserial":"1"} and I am separating with ":".
And I am getting data like this pSerial:"1"} but I want only 1 value.
NSURL *url = [NSURL URLWithString:strUrl];
NSData *respData = [NSData dataWithContentsOfURL:url];
NSString *strResp = [[NSString alloc]initWithData:respData encoding:NSUTF8StringEncoding];
NSString *approvalString = [[strResp componentsSeparatedByString:#":"] objectAtIndex:3];
NSLog(#"pSerial:%#",approvalString);
for Example :
SBJsonParser *jsonPar = [[SBJsonParser alloc] init];
NSError *error = nil;
NSArray *jsonObj = [jsonPar objectWithString:jsonString error:&error];
id jsonObj = [jsonPar objectWithString:jsonString error:&error];
if ([jsonObj isKindOfClass:[NSDictionary class]])
// treat as a dictionary, or reassign to a dictionary ivar
else if ([jsonObj isKindOfClass:[NSArray class]])
// treat as an array or reassign to an array ivar.
Then get the value :
NSMutableArrary *userMutArr = [NSMutableArray array];
for (NSDictionary *dict in jsonObj)
{
User *userObj = [[[User alloc] init] autorelease];
[userObj setFirstName:[dict objectForKey:#"firstName"]];
[userObj setLastName:[dict objectForKey:#"lastName"]];
[userObj setAge:[[dict objectForKey:#"age"] intValue]];
[userObj setAddress:[dict objectForKey:#"address"]];
[userObj setPhoneNumbers:[dict objectForKey:#"phoneNumber"]];
[userMutArr addObject:userObj];
}
Hope you will understand. and read some Documents. it will help you.
It looks like you are in need of JSON Parsing. Here, what you want is JSON Parsing, not separating data from the JSON Response. JSON is the format of the data in which data is formatted in Key-Value pairs. You can fetch the "Value" of any object using the "Key".
Your first two lines are correct.
NSURL *url = [NSURL URLWithString:strUrl];
NSData *respData = [NSData dataWithContentsOfURL:url];
Now, you can parse JSON Response like this :
NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:respData options:kNilOptions error:&error];
NSString *pSerial = [json objectForKey:#"pserial"];
This will give you the value of "pserial" from your response. Similarly, you can get the values for "success" and "message". You can check it using this line :
NSLog(#"pserial :: %#",pserial);
You need to parse the JSON Response String, you can use any JSON parser like:
https://github.com/stig/json-framework/
And in your code do:
NSString *strResp = [[NSString alloc]initWithData:respData encoding:NSUTF8StringEncoding];
NSDictionary *ResponseDictionary = [strResp JSONValue];
NSString * pSerial = (NSString*)[ResponseDictionary objectForKey:#"pserial"];
Dont separation by ":" just use JSONValue your response is like
// {"success":"true","message":"You have logged in","pserial":"1"}
// with SBJsonParser parse your object like this
NSDictionary *responseJson = [YOUR-OBJECT JSONValue];
Note: dont forget to add Json header file
Its better you use any OpenSource Json Parser
Here is a stack post Comparison of different Json Parser for iOS

How to Parse this JSON in Objective-C

I'm new in iPhone programming.
I have to parse this data in JSON in Objective-C.
{"success":1,"check":[{"ChkKey":"2","ChkDeb":"Connection 1","ChkSSID":"Netgear-1111","ChkIP":"192.168.2.103","ChkBlk":"0"}]}
I follow the example for parsing data with Json. But this JSON is so different.
It is composed by two Array.
How can i proceed?
Thanks - A.b.
How about trying something like this ...
//JSON string
NSString *jsonString = #"{\"success\":1,\"check\":[{\"ChkKey\":\"2\",\"ChkDeb\":\"Connection 1\",\"ChkSSID\":\"Netgear-1111\",\"ChkIP\":\"192.168.2.103\",\"ChkBlk\":\"0\"}]}";
//Parse JSON string into an NSDictionary
NSError *e = [[NSError alloc] init];
NSDictionary *jsonData = [NSJSONSerialization JSONObjectWithData:[jsonString dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:&e];
//Output the value of success
NSLog(#"Success:%#", [jsonData objectForKey:#"success"]);
//Get data in the check array
NSDictionary *checkData = [[jsonData objectForKey:#"check"] objectAtIndex:0];
//Output the value of ChkSSID
NSLog(#"ChkSSID:%#", [checkData objectForKey:#"ChkSSID"]);

Plist serialisation in Iphone?

I have an IPhone application in which i am using this code .
NSPropertyListFormat plistFormat;
NSDictionary *payloadDict = [NSPropertyListSerialization
propertyListWithData:subscriptionProduct.receipt
options:NSPropertyListImmutable
format:&plistFormat
error:nil];
where i am getting the subscriptionProduct.receipt correctly and reciept is an nsdata, which is declared inside the subscriptionProduct class.But after the conversion when i am trying to print payloadDict it is terned to be null.can anybody help me
Try getting the error out of the method and displaying it:
NSPropertyListFormat plistFormat;
NSError *parseError;
NSDictionary *payloadDict = [NSPropertyListSerialization
propertyListWithData:subscriptionProduct.receipt
options:NSPropertyListImmutable
format:&plistFormat
error:&parseError];
NSLog(#"payloadDict = %#", payloadDict);
NSLog(#"parseError = %#", parseError);
If parseError is nil, the property list serialization thinks it read the data properly. If not, its contents should tell you where to look.
Your comments seem to say that you want to construct a new NSDictionary that stores the object subscriptionProduct.receipt.
You can do this:
NSMutableDictionary *payloadDict = [NSMutableDictionary dictionary];
// Always check if values are nil before adding them to a dictionary.
if (subscriptionProduct.receipt)
[payloadDict setObject:subscriptionProduct.receipt forKey:#"receipt"];
If you want to load the receipt later, you can do this:
NSData *receiptData = [payloadDict objectForKey:#"receipt"];

NSDictionary to XML

I'm trying to convert a NSDictionary to XML. (I was successful in transforming NSDictionary to JSON). But now I need to transform NSDictionary to XML. Is there a built-in serializer in Objective-C like the one for JSON?
int r = arc4random() % 999999999;
//simulate my NSDictionary (to be turned into xml)
NSString *name = [NSString stringWithFormat:#"Posted using iPhone_%d", r];
NSString *stock_no = [NSString stringWithFormat:#"2342_%d", r];
NSString *retail_price = #"12345";
NSArray *keys = [NSArray arrayWithObjects:#"name", #"stock_no", #"retail_price", nil];
NSArray *objects = [NSArray arrayWithObjects:name,stock_no,retail_price, nil];
NSDictionary *theRequestDictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
NSDictionary *theFinalRequestDictionary = [NSDictionary dictionaryWithObject:theRequestDictionary forKey:#"product"];
...//other irrelevant code omitted
NSData *theBodyData = [NSPropertyListSerialization dataFromPropertyList:theFinalRequestDictionary format:NSPropertyListXMLFormat_v1_0 errorDescription:nil];
NSPropertyListFormat format;
id XMLed = [NSPropertyListSerialization propertyListFromData:theBodyData
mutabilityOption:NSPropertyListImmutable
format:&format
errorDescription:nil];
NSLog(#"the XMLed is this: %#", [NSString stringWithFormat:#"%#", XMLed]);
The NSLog doesn't print a string in XML format. It prints it like a NSDictionary.
What should I use to serialize my NSDictionary to XML?
propertyListFromData:... returns a "property list object", that is, depending on the contents of the data, an array or a dictionary. The thing that you're actually interested in (the xml) is returned by dataFromPropertyList:... and thus stored in your theBodyData variable.
Try this:
NSLog(#"XML: %#", [[[NSString alloc] initWithData:theBodyData encoding:NSUTF8StringEncoding] autorelease]);
There are many different varieties of XML. If you're not picky about the specific tags, and if the contents of your dictionary is limited to types used in property lists (NSString, NSNumber, NSDate, etc.) you can write your dictionary to a property list in one line:
[myDict writeToFile:somePath atomically:YES];
If you'd prefer to keep the XML in memory instead of writing to a file, use NSPropertyListSerialization as you're doing.