programing

JSON 직렬화 데이터를 NSDictionary로 변환하는 방법

muds 2023. 2. 25. 22:27
반응형

JSON 직렬화 데이터를 NSDictionary로 변환하는 방법

나는 이 방법을 사용해 왔다.

NSDictionary *jsonObject=[NSJSONSerialization 
       JSONObjectWithData:jsonData 
                  options:NSJSONReadingMutableLeaves 
                    error:nil];
NSLog(@"jsonObject is %@",jsonObject);

"jsonObject is null"이라고 표시되어 있습니다.
"error:nil"에 문제가 있습니까?
url이나 접속 방법을 사용하지 않습니다.
저는 json 파일을 가지고 있는데 그것을 표로 표시하고 싶습니다.

다음 코드를 사용해 보십시오.

NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseData
                                                     options:kNilOptions 
                                                       error:&error];

NSArray* latestLoans = [json objectForKey:@"loans"];

NSLog(@"loans: %@", latestLoans);

스위프트 코드를 보기 위해 여기에 있는 사람을 대비해서:

NSData에서 NSDictionary로

let dictionary:NSDictionary = NSKeyedUnarchiver.unarchiveObjectWithData(jsonData)! as NSDictionary

NSData에서 NSString으로

let resstr = NSString(data: res, encoding: NSUTF8StringEncoding)

json 입력을 확인합니다. 루트 요소가 사전도 배열도 아닐 수 있습니다.이 경우 NSJSONReadingAllowFragments를 옵션으로 지정해야 합니다.

#import <Foundation/Foundation.h>

int main(int argc, char *argv[]) {
    NSAutoreleasePool *p = [[NSAutoreleasePool alloc] init];

    NSData *jsonData = [@"{ \"key1\": \"value1\" }" dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *jsonObject=[NSJSONSerialization 
           JSONObjectWithData:jsonData 
                      options:NSJSONReadingMutableLeaves 
                        error:nil];
    NSLog(@"jsonObject is %@",jsonObject);

    [p release];
}

출력:

2012-09-26 16:06:51.610 Untitled[19164:707] jsonObject is {
    key1 = value1;
}
NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];

이것은 단지 톱 포스트의 더 간결한 버전이다.

Json을 변환하다IntoDict = JSON Serialization.jsonObject(데이터 포함!, 옵션: [])를 사용해 보십시오.NSDirectionary

언급URL : https://stackoverflow.com/questions/12603047/how-to-convert-json-serialized-data-to-nsdictionary

반응형