Objective-C JSon 실례 상세 설명

3336 단어 Objective-CJson
Objective-C JSon 실례 상세 설명
NSJSONserialization 을 사용 하면 JSon 과 Foundation 의 상호 전환 이 가능 합 니 다.다음은 Objective-c json 의 사용 을 구체 적 으로 소개 한다.
Json To Fundation
JSONobject Withdata 를 사용 하면 JSon 을 Foundation 으로 전환 할 수 있 습 니 다.JSon 의 맨 윗 층 은{}또는[]일 수 있 기 때문에 NSDictionary 와 NSArray 두 가지 형식 이 있 을 수 있 습 니 다.ObjectForKey 를 사용 하여 대응 하 는 대상 을 읽 습 니 다.

NSString* items = @"{"items":["item0","item1","item2"]}";
 
NSData *data= [items dataUsingEncoding:NSUTF8StringEncoding];
 
NSError *error = nil;
 
id jsonObject = [NSJSONSerialization JSONObjectWithData:data 
          options:NSJSONReadingAllowFragments 
          error:&error];
 
if ([jsonObject isKindOfClass:[NSDictionary class]]){
 
  NSDictionary *dictionary = (NSDictionary *)jsonObject;
 
  NSLog(@"Dersialized JSON Dictionary = %@", dictionary);
 
}else if ([jsonObject isKindOfClass:[NSArray class]]){
 
  NSArray *nsArray = (NSArray *)jsonObject;
 
  NSLog(@"Dersialized JSON Array = %@", nsArray);
 
} else {
 
  NSLog(@"An error happened while deserializing the JSON data.");
 
}
 
NSDictionary *dict = (NSDictionary *)jsonObject;
 
NSArray* arr = [dict objectForKey:@"items"];
NSLog(@"list is %@",arr);
Fundation To Json
dataWithJSonObject 를 사용 하면 Fundation 을 JSon 으로 변환 할 수 있 습 니 다.그 중에서 options:NSJSON Writing Pretty Printed 는 줄 별 출력 json 이 고 빈 칸 없 는 출력 은 option:kNilOptions 를 사용 합 니 다.
아래 코드 는 IOS 내 구 매 획득 상품 목록 입 니 다.가 져 오 면 내용 을 JSon 에 추가 합 니 다.

NSArray *myProduct = response.products;
NSDictionary *myDict;
NSMutableDictionary *dict = [NSMutableDictionary 
                dictionaryWithCapacity: 4];
 
for(int i = 0;i<myProduct.count;++i)
{
 
  //NSLog(@"----------------------");
  //NSLog(@"Product title: %@" ,[myProduct[i] localizedTitle]);
  //NSLog(@"Product description: %@" ,[myProduct[i] localizedDescription]);
  //NSLog(@"Product price: %@" ,[myProduct[i] price]);
  //NSLog(@"Product id: %@" ,[myProduct[i] productIdentifier]);
 
  myDict = [NSDictionary dictionaryWithObjectsAndKeys:
          [myProduct[i] localizedTitle], @"title",
          [myProduct[i] localizedDescription], @"desc",
          [myProduct[i] price], @"price",
          [myProduct[i] productIdentifier], @"product", nil];
 
  [dict setValue: myDict forKey: [myProduct[i] productIdentifier]];
}
if([NSJSONSerialization isValidJSONObject:dict])
{
  NSError* error;
  NSData *str = [NSJSONSerialization dataWithJSONObject:dict 
            options:kNilOptions error:&error];
  NSLog(@"Result: %@",[[NSString alloc]initWithData:str 
              encoding:NSUTF8StringEncoding]);
}
else
{
  NSLog(@"An error happened while serializing the JSON data.");
}    
 궁금 한 점 이 있 으 시 면 메 시 지 를 남기 거나 본 사이트 의 커 뮤 니 티 에 가서 토론 을 교류 하 세 요.읽 어 주 셔 서 감사합니다. 도움 이 되 셨 으 면 좋 겠 습 니 다.본 사이트 에 대한 지지 에 감 사 드 립 니 다!

좋은 웹페이지 즐겨찾기