Convert JSON String to Object - iphone

Trying to convert JSON String into the object
NSString *testString = #"OMJ=\"N.A.\"&SPJ=\"N.A.\"&OBJ=\"N.A.\"";
NSMutableDictionary *tags = [NSMutableDictionary new];
tags = [NSMutableDictionary dictionaryWithDictionary:[Utility convertJSONStringToObject:testString]];
Errror Message!
-[__NSCFConstantString objectFromJSONString]: unrecognized selector sent to instance!
After using the NSJSONSerialization the retun value for the dictionary JSON is null empty
NSDictionary *JSON =
[NSJSONSerialization JSONObjectWithData: [#"OMJ=\"N.A.\"&SPJ=\"N.A.\"&OBJ=\"N.A\"" dataUsingEncoding:NSUTF8StringEncoding]
options: NSJSONReadingMutableContainers
error: nil];
What i did wrong in my code. Any one advice me to fix the issue.
#thanks in advance

Related

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"]);

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.

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"];

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.

NSPropertyListSerialization after parsing an XML

I need to know if I am in the right track here. I am parsing an XML-RPC in iPhone (using the eczarny framework) and I am getting an array with objects. I create an NSData and store an object. After that I am trying to deserialize it but get en error.
Code:
NSArray *result = [response object];
NSData *data = [result objectAtIndex:0];
NSLog(#"Data %#",data);
NSDictionary * message = nil;
NSString * error = nil;
message = [NSPropertyListSerialization propertyListFromData:data mutabilityOption:NSPropertyListMutableContainers format:nil errorDescription:&error];
The nslog:
Data {
DESCRIPTION = "Standardverkn";
FLAGS = 0;
NAME = "Fenster OG3";
RECEIVER = "IEQ007:3";
SENDER = "IEQ0043:1";
}
The error:
-[__NSCFDictionary length]: unrecognized selector sent to instance 0x6e4bd50
What am I doing wrong?
[result objectAtIndex:0] is already an NSDictionary. You don't need to deserialize it. You can just directly use it as the message.
(If it is an NSData, the NSLog will show something like <12345678 9abcdef0 ...>.)