2012-09-23 2 views
0

누구나 IOS5에서 json 데이터를 구문 분석하는 방법을 알려줄 수 있습니까? 아래 JSON 데이터를 제공하고 있습니다.IOS5에서 JSON 데이터를 구문 분석하는 방법

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

올바른 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

으로 분석 데이터를 통해 걸어 갈 수 있습니다. 귀하의 경우에는

당신은 그에게 사전의 배열을 언급 JSON 문자열에 따라, 당신이있어 한 번 jsonObjects 당신이 당신의 JSON을 구문 분석 할 수 있습니다 이러한 방법으로

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 
} 

.. 데이터를 얻기 위해이 작업을 수행 string .. 자세한 내용은 Raywenderlich의 tutorial을 참조하십시오.

3

가 JSON 데이터가 올바르게 포맷되지 않았습니다 내가 코드 아래 사용하여 JSON을 구문 분석 할 때 오류가 발생합니다. 당신이 항목의 배열을 가지고 있기 때문에, 당신은 [ ... ]이 동봉해야합니다

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

지금 JSONObjectWithData가 (때문에 NSJSONReadingMutableContainers 플래그의) 당신에게 NSMutableArrayNSMutableDictionary의 객체를 제공

.

는 먼저 모든 NSLog의 JSON 또는 XML 문자열이 다음이 코드를 파싱 쓰기 시작, 구문 분석의 모든 유형에서

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