Creating a JSONObject in iOS5

Go To StackoverFlow.com

0

This answer seems to show how to make a JSONObject.

NSString *jsonString = @"[{\"id\": \"1\", \"name\":\"Aaa\"}, {\"id\": \"2\", \"name\":\"Bbb\"}]";
NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSError *e = nil;
NSMutableArray *json = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&e];
NSLog(@"%@", json);

The output looks like a json object. But then I tried the following:

NSLog(@"%@", [NSJSONSerialization dataWithJSONObject:json options:NSJSONWritingPrettyPrinted error:nil ]);

What I got back was

<5b0a2020 7b0a2020 20202269 6422203a 20223122 2c0a2020 2020226e 616d6522 203a2022 41616122 0a20207d 2c0a2020 7b0a2020 20202269 6422203a 20223222 2c0a2020 2020226e 616d6522 203a2022 42626222 0a20207d 0a5d>

This seems to show that it isn't a real JSONObject. How do you make one?

2012-04-04 01:12
by neuromancer


3

It may be a real JSONObject, but NSLog doesn't know how to display raw data... the "%@" bit in NSLog wants a NSString with an encoding, not NSData.

There are two ways I can see off the top of my head to tell if things worked out okay.

#1) use the [isValidJSONObject:] method

or

#2) re-parse the JSON object you just created and see if it comes out the way you created it. You can print out the NSData by doing something like:

NSError * error = nil;
NSData * jsonData = [NSJSONSerialization dataWithJSONObject:json options:NSJSONWritingPrettyPrinted error:&error ];
if(jsonData == nil)
{
    NSLog( @"error in parsing json data is %@", [error localizedDescription] );
} else {
    NSString * jsonString = [[NSString alloc] initWithData: jsonData encoding: NSUTF8StringEncoding];    
    NSLog( "json data is %@", jsonString );
}
2012-04-04 01:17
by Michael Dautermann
If I had an NSArray of NSStrings, how would I assign the whole array to a key and then turn that into a JSONobject - neuromancer 2012-04-04 01:27
A JSONObject is just a NSArray - neuromancer 2012-04-04 01:32
You can create JSON objects via NSJSONSerialization either from data or a stream (but not an array or a dictionary). You'd need to convert an array to NSData to do the JSON conversion. Take a look at this related question and you might find the answer you seek - Michael Dautermann 2012-04-04 01:33