iOS JSON NSString 解析
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10200790/
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
iOS JSON NSString Parse
提问by user1120008
I have a JSON string as an NSString object in iOS. I want to parse this and pull out the given parameters in the JSON string. Is there a efficient way to parse this or is the only way to search for substrings etc.?
我有一个JSON字符串作为iOS的一个NSString对象。我想解析它并提取 JSON 字符串中的给定参数。有没有一种有效的方法来解析这个或者是搜索子字符串等的唯一方法?
回答by jonkroll
The way to do it with iOS 5 is to use the NSJSONSerialization
class. You will want to first convert your string to an NSData object, and call the class method JSONObjectWithData
在 iOS 5 中做到这一点的方法是使用NSJSONSerialization
类。您需要先将字符串转换为 NSData 对象,然后调用类方法JSONObjectWithData
NSData *jsonData = [myJsonString dataUsingEncoding:NSUTF8StringEncoding];
NSError *e;
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:jsonData options:nil error:&e];
Note that JSONObjectWithData
will return either an NSDictionary or an NSArray, depending whether your JSON string represents an a dictionary or an array.
请注意,这JSONObjectWithData
将返回 NSDictionary 或 NSArray,具体取决于您的 JSON 字符串是代表字典还是数组。