[英]How to parse my JSON data in IOS5
誰能告訴我如何在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
}
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]);
}
}
在任何類型的解析中,首先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
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.