如何在IOS5中解析我的JSON数据

时间:2012-09-23 09:49:36

标签: iphone objective-c json ios5 ios5.1

任何人都可以告诉我如何在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 
}

2 个答案:

答案 0 :(得分:3)

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

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

现在JSONObjectWithData为您提供NSMutableArrayNSMutableDictionary个对象(因为NSJSONReadingMutableContainers标志)。

您可以使用

浏览已解析的数据
for (NSMutableDictionary *dict in jsonObjects) {
    for (NSString *key in dict) {
        NSLog(@"%@ is %@",key, [dict objectForKey:key]);
    }
}

答案 1 :(得分:0)

在任何类型的解析中,首先是NSLog JSON或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的tutorial