Plist serialisation in Iphone? - 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"];

Related

value stored during initialization is never read

I am trying parse the google api so that I can retrieve the address and its data.
I get two errors that are on the commented lines. Why am I getting these errors.
I allocated the dit so I should have to release it correct.
Here is my code to retrieve the data
NSURL *url=[NSURL URLWithString:str];
NSData *data=[[NSData alloc]initWithContentsOfURL:url];
NSString *str1=[[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]autorelease];
NSDictionary *dit=[[[NSDictionary alloc]init]autorelease];//value stored to dit during initialization is never read
dit=[str1 JSONValue];
NSArray *dit1=(NSArray *) [dit objectForKey:#"results"];
NSDictionary *dit3=[[dit1 objectAtIndex:0]objectForKey:#"geometry"];
NSDictionary *dit4=[dit3 objectForKey:#"bounds"];
NSDictionary *northeast=[dit4 objectForKey:#"northeast"];
NSDictionary *lt=[northeast objectForKey:#"lat"];
NSDictionary *southwest=[dit4 objectForKey:#"southwest"];
NSDictionary *lng=[southwest objectForKey:#"lng"];
Probably the issue is this:
NSDictionary *dit=[[[NSDictionary alloc]init]autorelease];
dit=[str1 JSONValue];
You create an empty dictionary, then never use it but instead overwrite the value with the one returned from JSONValue. This code should be:
NSDictionary *dit=[str1 JSONValue];

Parse json in objective-c for my iphone app

i have a problem parsing my json data for my iPhone app, I am new to objective-C. I need to parse the json and get the values to proceed. Please help. This is my JSON data:
[{"projId":"5","projName":"AdtvWorld","projImg":"AdtvWorld.png","newFeedCount":"0"},{"projId":"1","projName":"Colabus","projImg":"Colabus.png","newFeedCount":"0"},{"projId":"38","projName":"Colabus Android","projImg":"ColabusIcon.jpg","newFeedCount":"0"},{"projId":"25","projName":"Colabus Internal Development","projImg":"icon.png","newFeedCount":"0"},{"projId":"26","projName":"Email Reply Test","projImg":"","newFeedCount":"0"},{"projId":"7","projName":"PLUS","projImg":"7plusSW.png","newFeedCount":"0"},{"projId":"8","projName":"Stridus Gmail Project","projImg":"scr4.png","newFeedCount":"0"}]
On iOS 5 or later you can use NSJSONSerialization. If you have your JSON data in a string you can do:
NSError *e = nil;
NSData *data = [stringData dataUsingEncoding:NSUTF8StringEncoding];
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData: data options: NSJSONReadingMutableContainers error: &e];
Edit To get a specific value:
NSDictionary *firstObject = [jsonArray objectAtIndex:0];
NSString *projectName = [firstObject objectForKey:#"projName"];
I would recommend using JSONKit library for parsing.
Here's a tutorial on how to use it.
You will basically end up with a dictionary and use objectForKey with your key to retrive the values.
JSONKit
or
NSJSONSerialization(iOS 5.0 or later)
I have had success using SBJson for reading and writing json.
Take a look at the documentation here and get an idea of how to use it.
Essentially, for parsing, you just give the string to the SBJsonParser and it returns a dictionary with an objectForKey function. For example, your code might look something like:
NSDictionary* parsed = [[[SBJsonParser alloc] init] objectWithString: json];
NSString* projId = [parsed objectForKey:#"projId"];
Use SBJson
SBJsonParser *parser = [[SBJsonParser alloc] init];
NSMutableDictionary *dicRes = [parser objectWithString:stringFromServer error:nil];
No need to use third party classes. Objective-c already includes handling JSON.
The class NSJSONSerialization expects an NSData object or reads from a URL. The following was tested with your JSON string:
NSString *json; // contains your example with escaped quotes
NSData *jsonData = [json dataUsingEncoding:NSUTF8StringEncoding];
NSError *error;
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:jsonData
options:NSJSONReadingAllowFragments error:&error]
For more options with NSJSONSerialization see the documentation.

JSONKit: changing and serializing JSON attribute's value

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.

Help needed with json iphone

I m receiving data from the server. Now when i m deserializing it i m getting an array with key value. Now the first object of the array is my whole NSDictionary item from which i have to extract data using keys. I m stuck here i tried using different things like extracting them in sets but it disturbs there arrangement. I m pretty new in the field . please can anyone help me out here. How to get that array into a NSDictionary object or extract info using keys from that array. Thanks.
NSData *responseData = [[request responseString] dataUsingEncoding:NSUTF8StringEncoding];
NSError *err = nil;
NSDictionary *dataArray = [[CJSONDeserializer deserializer]deserialize:responseData error:&err];
it gves an array as output to me.
How about: NSDictionary *myDictionary = [myArray objectAtIndex:0];
I highly recommend the SBJson framework as a production ready library for dealing with just such issues.

How to store values inside Plist and read while runtime in iphone 3.0?

how to store values inside Plist and read while runtime in iphone 3.0?.
Thanks in Advance.
If you have an array or dictionary that contains only "standard" data types like strings, dates, numbers, arrays, and dictionaries, you can save the contents to a .plist file with -[NSArray writeToFile:atomically:] or -[NSDictionary writeToFile:atomically:]. To read the file, use -initWithContentsOfFile:.
Note that the application bundle is not writable on iPhone OS devices so you will have to store the file in your app's Documents directory.
This solution can be applied to both NSArray and NSDictionary.
Use this method to make a NSData from property list and use writeToFile to persist it to disk.
[NSPropertyListSerialization dataFromPropertyList:(id)plist
format:(NSPropertyListFormat)format
errorDescription:(NSString **)errorString];
Use this method to read property list from NSData.
[NSPropertyListSerialization propertyListFromData:(NSData *)data
mutabilityOption:(NSPropertyListMutabilityOptions)opt
format:(NSPropertyListFormat *)format
errorDescription:(NSString **)errorString];
Example:
NSPropertyListFormat format = 0;
NSString *errorString = nil;
NSDictionary *dataDict = [NSPropertyListSerialization propertyListFromData:data
mutabilityOption:NSPropertyListMutableContainersAndLeaves
format:&format errorDescription:&errorString];
if (errorString != nil) {
NSLog(errorString);
[errorString release];
}
NSLog(#"got dictionary:%#", dataDict);
errorString = nil;
NSData *data = [NSPropertyListSerialization dataFromPropertyList:dataDict
format:NSPropertyListXMLFormat_v1_0 errorDescription:errorString];
NSLog(#"plist data:%#", data); // convert to NSString to get <plist>