2013-04-14

Cocoa Objective-C JSON encode and decode

Views: 10474 | Add Comments

KISS – Keep It Simple, Stupid!

The NSJSONSerialization limited top level objects to NSArray and NSDcitionary, but with this tool, you can encode primative objects, such as integer, float, string, array, dictionary to JSON string, and vice verse.

You can decode the json string contains only string to Objective-C object, like "a" to an NSString, and it works for numbers, 123 will decode to NSNumber.

#import <Foundation/Foundation.h>

NSString *json_encode(id obj){
	BOOL is_primative = false;
	if(![obj isKindOfClass:[NSArray class]] && ![obj isKindOfClass:[NSDictionary class]]){
		is_primative = true;
		obj = [NSArray arrayWithObject: obj];
	}
	id data = [NSJSONSerialization dataWithJSONObject:obj options:0 error:nil];
	NSError *err = nil;
	NSString *str = [[NSString alloc] initWithData:data encoding:[NSString defaultCStringEncoding]];
	if(err){
		return nil;
	}
	if(is_primative){
		str = [str substringWithRange:NSMakeRange(1, [str length]-2)];
	}
	return str;
}

id json_decode(NSString *str){
	str = [str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
	BOOL is_primative = false;
	unichar ch = [str characterAtIndex:0];
	if(ch == '"' || (ch != '[' && ch != '{')){
		is_primative = true;
		str = [NSString stringWithFormat:@"[%@]", str, nil];
	}
	NSData* data = [str dataUsingEncoding:[NSString defaultCStringEncoding]];
	NSError *err = nil;
	id obj = [NSJSONSerialization JSONObjectWithData:data options:0 error:&err];
	if(err){
		return nil;
	}
	if(is_primative){
		obj = [obj objectAtIndex: 0];
	}
	return obj;
}

int main(int argc, char **argv){
	NSArray *arr = [NSArray arrayWithObjects: @"a", @"b", nil];
	NSLog(@"%@", json_encode(@"abc"));
	NSLog(@"%@", json_encode(arr));
	NSLog(@"%@", json_decode(@"[1, 2, \"abc\"]"));
	NSLog(@"%@", json_decode(@"\"abc\""));
	NSLog(@"%@", json_decode(@"\"%\""));
	return 0;
}

A bunch of simpler Objective-C classes and functions(Standard Objective C Library): https://github.com/ideawu/soc

Posted by ideawu at 2013-04-14 14:38:47

Leave a Comment