Is it possible if I have a NSString and I want to use NSJSONSerialization? How do I do this?

- 7,331
- 5
- 34
- 66

- 14,290
- 50
- 150
- 253
-
1In case performance is your priority, JSONKit is a better alternative. – Danra Jan 14 '12 at 00:08
-
1There is a good tutorial at http://www.raywenderlich.com/5492/working-with-json-in-ios-5 concerning the use of NSJSONSerialization. – Dean Jan 13 '12 at 23:56
4 Answers
First you will need to convert your NSString
to NSData
by doing the following
NSData *data = [stringData dataUsingEncoding:NSUTF8StringEncoding];
then simply use the JSONObjectWithData
method to convert it to JSON
id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];

- 85,596
- 89
- 230
- 327
-
3for convenience, you can put this code into NSJSONSerialization Category. – jianpx Nov 24 '13 at 07:37
-
Use 'NSJSONSerialization JSONObjectWithData' carefully, as, although it has an NSError* parameter, it might throw an exceptions when an error occurs! It is recommendable to enclose it with an '@try {} @catch(...)' block. – LaborEtArs Nov 19 '17 at 14:21
You need to convert your NSString
to NSData
, at that point you can use the +[NSJSONSerialization JSONObjectWithData:options:error:]
method.
NSString * jsonString = YOUR_STRING;
NSData * data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSError * error = nil;
id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
if (!json) {
// handle error
}

- 759
- 5
- 16
You can convert your string to NSData by saying:
NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
You can then use it with NSJSONSerialization
. Note however that NSJSONSerialization
is iOS5 only, so you might be better off using a library like TouchJSON or JSONKit, both of which let you work directly with strings anyway, saving you the step of converting to NSData.

- 87,323
- 22
- 191
- 272

- 40,865
- 11
- 112
- 103
I wrote a blog post that demonstrates how to wrap the native iOS JSON class in a general protocol together with an implementation that use the native iOS JSON class.
This approach makes it a lot easier to use the native functionality and reduces the amount of code you have to write. Furthermore, it makes it a lot easier to switch out the native implementation with, say, JSONKit, if the native one would prove to be insufficient.
http://danielsaidi.com/blog/2012/07/04/json-in-ios
The blog post contains all the code you need. Just copy / paste :)
Hope it helps!

- 6,079
- 4
- 27
- 29