I have a NSString *str = @"abcd"
, and I want to serialize it as JSON String which becomes
"abcd"
.
How should I do?
I have tried this
NSJSONSerialization from NSString, but it doesn't work. The returned id
is 0x0
.
This is my tricky code what I am using now to do this
NSDictionary *dict = @{@"result": str};
NSData *data = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
NSString *body = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
body = [body substringFromIndex:14];
body = [body substringToIndex:body.length - 2];
Finally
I read spec about JSON and know that OC follows old JSON spec that just thinks object and array is valid. That's the reason why NSJSONSerialization
cannot serialize JSON string.