iOS 7中的JSON解析 [英] JSON Parsing in iOS 7
问题描述
我正在为现有网站创建应用。他们目前拥有以下格式的JSON:
I am creating an app for as existing website. They currently has the JSON in the following format :
[
{
"id": "value",
"array": "[{\"id\" : \"value\"} , {\"id\" : \"value\"}]"
},
{
"id": "value",
"array": "[{\"id\" : \"value\"},{\"id\" : \"value\"}]"
}
]
他们在使用Javascript转义\字符后解析。
which they parse after escaping the \ character using Javascript.
我的问题是当我使用iOS解析它时以下命令:
My problem is when i parse it in iOS using the following command :
NSArray *result = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&localError];
并执行此操作:
NSArray *Array = [result valueForKey:@"array"];
而不是数组
我得到了 NSMutableString
object。
Instead of an Array
I got NSMutableString
object.
-
该网站已经投入生产,所以我不能问他们改变现有结构以返回正确的
JSON
对象。对他们来说这将是很多工作。
The website is already in production so I just cant ask them to change their existing structure to return a proper
JSON
object. It would be a lot of work for them.
因此,在他们改变基础结构之前,有什么办法可以让它在<$ c中运行$ c> iOS 就像他们在网站上
? javascript
一样
So, until they change the underlying stucture, is there any way i can make it work in iOS
like they do with javascript
on their website
?
任何帮助/建议对我都非常有帮助。
Any help/suggestion would be very helpful to me.
推荐答案
正确的JSON应该看起来像:
The correct JSON should presumably look something like:
[
{
"id": "value",
"array": [{"id": "value"},{"id": "value"}]
},
{
"id": "value",
"array": [{"id": "value"},{"id": "value"}]
}
]
但是,如果你再坚持这在你的问题中提供的格式,你需要做的字典可变用 NSJSONReadingMutableContainers
,然后调用 NSJSONSerialization
再次为每个数组
条目:
But, if you're stuck this the format provided in your question, you need to make the dictionary mutable with NSJSONReadingMutableContainers
and then call NSJSONSerialization
again for each of those array
entries:
NSMutableArray *array = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
if (error)
NSLog(@"JSONObjectWithData error: %@", error);
for (NSMutableDictionary *dictionary in array)
{
NSString *arrayString = dictionary[@"array"];
if (arrayString)
{
NSData *data = [arrayString dataUsingEncoding:NSUTF8StringEncoding];
NSError *error = nil;
dictionary[@"array"] = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
if (error)
NSLog(@"JSONObjectWithData for array error: %@", error);
}
}
这篇关于iOS 7中的JSON解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!