我们有json文件(content.json)。我们需要获取数据表单.json文件,然后放入NSMutablearray。我们试过这个
NSString* path = [[NSBundle mainBundle] pathForResource:@"content" ofType:@"json"];
NSString* jsonString = [[NSString alloc] initWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
NSData* jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:nil];
id allKeys = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONWritingPrettyPrinted error:&jsonError];
NSLog(@"Key *** %@",allKeys);
for (int i=0; i<[allKeys count]; i++) {
NSDictionary *arrayResult = [allKeys objectAtIndex:i];
NSLog(@"name=%@",[arrayResult objectForKey:@"Description"]);
}
allKeys
值为空
JsonString is
[
{
"ID": “2”,
"MessageType": "0",
"Description": "Promotions”,
"ExpiryDateTime": "2015-07-10 12:00:00",
"Html": "<div class=\"ad_box\"><img class=\"banner\" src=\"jewellery.jpg\"\/><h3>"Hot" Items<ul \/><\/div>"
},
{
"ID": "4",
"MessageType": "1",
"Description": "Offers”,
"ExpiryDateTime": "2015-07-09 2:00:00",
"Html": "<div class=\"ad_box\"><img class=\"banner\" src=\"Williams-Petersan.jpg\"\/><h3>"Hot" Items - 2<ul \/><\/div>"
}
{
"ID": “6”,
"MessageType": “2”,
"Description": "Invitations”,
"ExpiryDateTime": "2015-07-09 3:00:00",
"Html": "<div class=\"ad_box\"><img class=\"banner\" src=\"Puma.jpg\"\/><h3>"Hot" Items - 2<ul \/><\/div>"
}
]
我们需要将描述数据放入ArrayResult
请指导我们
答案 0 :(得分:0)
您的json无效 - 请注意ID 2或6周围的unicode引号 - ID 4很好 - 有多个错误,可以轻松修复:)例如通过使用一些在线儿子验证器网站/支持的编辑器
代码本身看起来没问题
<强> BUT 强>
它不会是一个可变数组;)它将是不可变的。如果您想要Mutability,请将NSJSONReadingMutableContainers传递给JSON
答案 1 :(得分:0)
您不需要在NSString
之前制作NSData
。只需使用类方法dataWithContentsOfFile:
即可。要使数组可变,只需在序列化时添加命令mutableCopy
:
NSString* path = [[NSBundle mainBundle] pathForResource:@"content" ofType:@"json"];
NSData* jsonData = [NSData dataWithContentsOfFile:path];
id allKeys = [[NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:nil]mutableCopy];
NSLog(@"Key *** %@", allKeys);
for (int i=0; i<[allKeys count]; i++) {
NSDictionary *arrayResult = [allKeys objectAtIndex:i];
NSLog(@"name = %@",[arrayResult objectForKey:@"Description"]);
}
这是正确的json数据,可以使用代码:
[
{
"ID": "2",
"MessageType": "0",
"Description": "Promotions",
"ExpiryDateTime": "2015-07-10 12:00:00",
"Html": "<div class=\"ad_box\"><img class=\"banner\" src=\"jewellery.jpg\"\/><h3>\"Hot\" Items<ul \/><\/div>"
},
{
"ID": "4",
"MessageType": "1",
"Description": "Offers",
"ExpiryDateTime": "2015-07-09 2:00:00",
"Html": "<div class=\"ad_box\"><img class=\"banner\" src=\"Williams-Petersan.jpg\"\/><h3>\"Hot\" Items - 2<ul \/><\/div>"
},
{
"ID": "6",
"MessageType": "2",
"Description": "Invitations",
"ExpiryDateTime": "2015-07-09 3:00:00",
"Html": "<div class=\"ad_box\"><img class=\"banner\" src=\"Puma.jpg\"\/><h3>\"Hot\" Items - 2<ul \/><\/div>"
},
]