ios 来自 NSString 的 NSJSONSerialization
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8858814/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
NSJSONSerialization from NSString
提问by aherlambang
Is it possible if I have a NSString and I want to use NSJSONSerialization? How do I do this?
如果我有一个 NSString 并且我想使用 NSJSONSerialization,这可能吗?我该怎么做呢?
回答by Jakub Arnold
First you will need to convert your NSString
to NSData
by doing the following
首先,您需要通过执行以下操作将您的转换NSString
为NSData
NSData *data = [stringData dataUsingEncoding:NSUTF8StringEncoding];
then simply use the JSONObjectWithData
method to convert it to JSON
然后只需使用该JSONObjectWithData
方法将其转换为 JSON
id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
回答by sho
You need to convert your NSString
to NSData
, at that point you can use the +[NSJSONSerialization JSONObjectWithData:options:error:]
method.
您需要将您的 转换NSString
为NSData
,此时您可以使用该+[NSJSONSerialization JSONObjectWithData:options:error:]
方法。
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
}
回答by Nick Lockwood
You can convert your string to NSData by saying:
您可以通过以下方式将字符串转换为 NSData:
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.
然后您可以将它与NSJSONSerialization
. 但是请注意,这NSJSONSerialization
仅适用于 iOS5,因此您最好使用像 TouchJSON 或 JSONKit 这样的库,这两种库都可以让您直接处理字符串,从而节省了转换为 NSData 的步骤。
回答by Daniel Saidi
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.
我写了一篇博客文章,演示了如何将原生 iOS JSON 类与使用原生 iOS JSON 类的实现一起包装在通用协议中。
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.
这种方法可以更轻松地使用本机功能并减少您必须编写的代码量。此外,如果本机实现被证明是不够的,那么使用 JSONKit 切换本机实现会变得更加容易。
http://danielsaidi.com/blog/2012/07/04/json-in-ios
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!
希望能帮助到你!