NSJSONSerialization from NSString

廉价感情. 提交于 2019-11-26 16:04:16

问题


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


回答1:


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



回答2:


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
}



回答3:


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.




回答4:


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!



来源:https://stackoverflow.com/questions/8858814/nsjsonserialization-from-nsstring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!