0

谁能告诉我如何在 IOS5 中解析我的 json 数据。我在下面提供我的 JSON 数据:

{
 "fieldType" : "Alphanumeric",
 "fieldName" : "Name"
},{
 "fieldType" : "Numeric",
 "fieldName" : "Card Num"
},{
 "fieldType" : "Alphanumeric",
 "fieldName" : "Pin Num"
}

这个 JSON 格式也是正确的还是我需要更改 JSON 格式?当我尝试使用以下代码解析 JSON 时,出现错误:

操作无法完成。(可可错误 3840。)

我正在使用的代码:

NSError *error = nil;
NSData *jsonData = [filedList dataUsingEncoding:[NSString defaultCStringEncoding]];
if (jsonData) 
{
    id jsonObjects = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];

    if (error)
    {
        NSLog(@"error is %@", [error localizedDescription]);
        // Handle Error and return
        return;

    }
    NSArray *keys = [jsonObjects allKeys];

    // values in foreach loop
    for (NSString *key in keys)
    {
        NSLog(@"%@ is %@",key, [jsonObjects objectForKey:key]);
    }                
} 
else 
{
    // Handle Error 
}
4

2 回答 2

3

JSON 数据的格式不正确。由于您有一系列项目,因此您需要将其包含在[ ... ]

[
    {
     "fieldType" : "Alphanumeric",
     "fieldName" : "Name"
    },{
     "fieldType" : "Numeric",
     "fieldName" : "Card Num"
    },{
     "fieldType" : "Alphanumeric",
     "fieldName" : "Pin Num"
    }
]

现在JSONObjectWithData给你一个NSMutableArray对象NSMutableDictionary(因为 NSJSONReadingMutableContainers 标志)。

您可以浏览解析的数据

for (NSMutableDictionary *dict in jsonObjects) {
    for (NSString *key in dict) {
        NSLog(@"%@ is %@",key, [dict objectForKey:key]);
    }
}
于 2012-09-23T10:02:46.487 回答
0

在任何类型的解析中,首先是NSLogJSON 或 XML 字符串,然后开始编写解析代码。

在你的情况下,根据你提到的 JSON 字符串,它是一个字典数组,一旦你得到你的 jsonObjects,就这样做来获取你的数据。

 id jsonObjects = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
NSLog(@"%@",jsonObjects);
// as per your example its an array of dictionaries so

NSArray* array = (NSArray*) jsonObjects;
for(NSDictionary* dict in array)
{
NSString* obj1 = [dict objectForKey:@"fieldType"];
NSString* obj2 = [dict objectForKey:@"fieldName"];

enter code here
enter code here
}

通过这种方式,您可以解析您的 json 字符串。有关更多详细信息,请参阅 Raywenderlich 的本教程

于 2012-09-23T10:07:27.960 回答