2012-09-23 94 views
0

任何人都可以告訴我如何解析我的JSON數據IOS5。我下面提供我的JSON數據:如何解析我的JSON數據IOS5

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

也是這個JSON格式正確或是否需要改變JSON格式?當我嘗試解析JSON使用下面的代碼我得到一個錯誤:

The operation couldn’t be completed. (Cocoa error 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 
} 
+0

使用http://jsonlint.com來驗證您的JSON。這是無效的 –

回答

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

3

JSON數據格式不正確。既然你有一個項目數組,你需要在[ ... ]附上這樣的:

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

現在JSONObjectWithData給你NSMutableDictionaryNSMutableArray的對象(因爲NSJSONReadingMutableContainers標誌)。

你可以通過分析數據與

for (NSMutableDictionary *dict in jsonObjects) { 
    for (NSString *key in dict) { 
     NSLog(@"%@ is %@",key, [dict objectForKey:key]); 
    } 
}