Objective-C JSon 실례 상세 설명
3336 단어 Objective-CJson
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 JsondataWithJSonObject 를 사용 하면 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.");
}
궁금 한 점 이 있 으 시 면 메 시 지 를 남기 거나 본 사이트 의 커 뮤 니 티 에 가서 토론 을 교류 하 세 요.읽 어 주 셔 서 감사합니다. 도움 이 되 셨 으 면 좋 겠 습 니 다.본 사이트 에 대한 지지 에 감 사 드 립 니 다!
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
PreferenceBundle에서 오른쪽 상단에 Respring 버튼을 클릭합니다.만나서 반갑습니다, Minazuki라고합니다. 프로필 이름 : Minazuki_dev Twitter : Repo : 아직 중학생이므로 말이 이상한 곳이 있습니다만 용서해 주세요… 🙏 theos (Mac이든 단품이든 ...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.