반응형
JSON과 Objective-C를 해석하려면 어떻게 해야 하나요?
나는 아이폰을 처음 본다.이 데이터를 해석하고 활동 세부사항, 이름, 성을 얻기 위해 따라야 할 절차를 알려주시겠습니까?
{
"#error": false,
"#data": {
"": {
"activity_id": "35336",
"user_id": "1",
"user_first_name": "Chandra Bhusan",
"user_last_name": "Pandey",
"time": "1300870420",
"activity_details": "Good\n",
"activity_type": "status_update",
"photo_url": "http://184.73.155.44/hcl-meme/QA_TEST/sites/default/files/pictures/picture-1627435117.jpg"
},
"boolean": "1",
"1": {
"1": {
"photo_1_id": "9755"
},
"activity_id": "35294",
"album_name": "Kalai_new_Gallery",
"user_id": "31",
"album_id": "9754",
"user_first_name": "Kalaiyarasan",
"user_last_name": "Balu",
"0": {
"photo_0_id": "9756"
},
"time": "1300365758",
"activity_type": "photo_upload",
"photo_url": "http://184.73.155.44/hcl-meme/QA_TEST/"
},
"3": {
"activity_id": "35289",
"user_id": "33",
"user_first_name": "Girija",
"user_last_name": "S",
"time": "1300279636",
"activity_details": "girija Again\n",
"activity_type": "status_update",
"photo_url": "http://184.73.155.44/hcl-meme/QA_TEST/sites/default/files/pictures/picture-33-6361851323080768.jpg"
},
"2": {
"owner_first_name": "Girija",
"activity_id": "35290",
"activity_details": "a:2:{s:4:\"html\";s:51:\"!user_fullname and !friend_fullname are now friends\";s:4:\"type\";s:10:\"friend_add\";}",
"activity_type": "friend accept",
"owner_last_name": "S",
"time": "1300280400",
"photo_url": "http://184.73.155.44/hcl-meme/QA_TEST/sites/default/files/pictures/picture-33-6361851323080768.jpg",
"owner_id": "33"
},
"4": {
"activity_id": "35288",
"user_id": "33",
"user_first_name": "Girija",
"user_last_name": "S",
"time": "1300279530",
"activity_details": "girija from mobile\n",
"activity_type": "status_update",
"photo_url": "http://184.73.155.44/hcl-meme/QA_TEST/sites/default/files/pictures/picture-33-6361851323080768.jpg"
}
}
}
OS X v10.7 및 iOS 5의 론칭의 관점에서는, 우선, Apple이 제공하는 JSON 파서를 추천합니다.타사 옵션은 런타임에 해당 클래스를 사용할 수 없는 경우에만 예비로 사용하십시오.
예를 들어 다음과 같습니다.
NSData *returnedData = ...JSON data, probably from a web request...
// probably check here that returnedData isn't nil; attempting
// NSJSONSerialization with nil data raises an exception, and who
// knows how your third-party library intends to react?
if(NSClassFromString(@"NSJSONSerialization"))
{
NSError *error = nil;
id object = [NSJSONSerialization
JSONObjectWithData:returnedData
options:0
error:&error];
if(error) { /* JSON was malformed, act appropriately here */ }
// the originating poster wants to deal with dictionaries;
// assuming you do too then something like this is the first
// validation step:
if([object isKindOfClass:[NSDictionary class]])
{
NSDictionary *results = object;
/* proceed with results as you like; the assignment to
an explicit NSDictionary * is artificial step to get
compile-time checking from here on down (and better autocompletion
when editing). You could have just made object an NSDictionary *
in the first place but stylistically you might prefer to keep
the question of type open until it's confirmed */
}
else
{
/* there's no guarantee that the outermost object in a JSON
packet will be a dictionary; if we get here then it wasn't,
so 'object' shouldn't be treated as an NSDictionary; probably
you need to report a suitable error condition */
}
}
else
{
// the user is using iOS 4; we'll need to use a third-party solution.
// If you don't intend to support iOS 4 then get rid of this entire
// conditional and just jump straight to
// NSError *error = nil;
// [NSJSONSerialization JSONObjectWithData:...
}
수레바퀴를 재발명하지 마세요.json-framework 같은 것을 사용합니다.
json-framework를 사용하기로 결정했을 경우 JSON 문자열을 다음과 같이 해석합니다.NSDictionary
:
SBJsonParser* parser = [[[SBJsonParser alloc] init] autorelease];
// assuming jsonString is your JSON string...
NSDictionary* myDict = [parser objectWithString:jsonString];
// now you can grab data out of the dictionary using objectForKey or another dictionary method
NSString* path = [[NSBundle mainBundle] pathForResource:@"index" ofType:@"json"];
//将文件内容读取到字符串中,注意编码NSUTF8StringEncoding 防止乱码,
NSString* jsonString = [[NSString alloc] initWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
//将字符串写到缓冲区。
NSData* jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSError *jsonError;
id allKeys = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONWritingPrettyPrinted error:&jsonError];
for (int i=0; i<[allKeys count]; i++) {
NSDictionary *arrayResult = [allKeys objectAtIndex:i];
NSLog(@"name=%@",[arrayResult objectForKey:@"storyboardName"]);
}
파일:
[
{
"ID":1,
"idSort" : 0,
"deleted":0,
"storyboardName" : "MLMember",
"dispalyTitle" : "76.360779",
"rightLevel" : "10.010490",
"showTabBar" : 1,
"openWeb" : 0,
"webUrl":""
},
{
"ID":1,
"idSort" : 0,
"deleted":0,
"storyboardName" : "0.00",
"dispalyTitle" : "76.360779",
"rightLevel" : "10.010490",
"showTabBar" : 1,
"openWeb" : 0,
"webUrl":""
}
]
NSJON Serialization을 사용한JSON 해석
NSString* path = [[NSBundle mainBundle] pathForResource:@"data" ofType:@"json"];
//Here you can take JSON string from your URL ,I am using json file
NSString* jsonString = [[NSString alloc] initWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
NSData* jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSError *jsonError;
NSArray *jsonDataArray = [NSJSONSerialization JSONObjectWithData:[jsonString dataUsingEncoding:NSUTF8StringEncoding] options:kNilOptions error:&jsonError];
NSLog(@"jsonDataArray: %@",jsonDataArray);
NSDictionary *jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&jsonError];
if(jsonObject !=nil){
// NSString *errorCode=[NSMutableString stringWithFormat:@"%@",[jsonObject objectForKey:@"response"]];
if(![[jsonObject objectForKey:@"#data"] isEqual:@""]){
NSMutableArray *array=[jsonObject objectForKey:@"#data"];
// NSLog(@"array: %@",array);
NSLog(@"array: %d",array.count);
int k = 0;
for(int z = 0; z<array.count;z++){
NSString *strfd = [NSString stringWithFormat:@"%d",k];
NSDictionary *dicr = jsonObject[@"#data"][strfd];
k=k+1;
// NSLog(@"dicr: %@",dicr);
NSLog(@"Firstname - Lastname : %@ - %@",
[NSMutableString stringWithFormat:@"%@",[dicr objectForKey:@"user_first_name"]],
[NSMutableString stringWithFormat:@"%@",[dicr objectForKey:@"user_last_name"]]);
}
}
}
콘솔 출력은 다음과 같습니다.
이름 - 성 : 찬드라 부산 - 판데이
이름 - 성 : Kalaiyarasan - Balu
이름 - 성 : (null) - (null)
이름 - 성 : 기리자 - S
이름 - 성 : 기리자 - S
이름 - 성 : (null) - (null)
- JSON의 해석에는 Touch JSON을 추천합니다.
알렉스에 대한 당신의 의견에 답하기 위해서요다음은 반환되는 json 사전에서 activity_details, last_name 등의 필드를 가져올 수 있는 빠른 코드입니다.
NSDictionary *userinfo=[jsondic valueforKey:@"#data"]; NSDictionary *user; NSInteger i = 0; NSString *skey; if(userinfo != nil){ for( i = 0; i < [userinfo count]; i++ ) { if(i) skey = [NSString stringWithFormat:@"%d",i]; else skey = @""; user = [userinfo objectForKey:skey]; NSLog(@"activity_details:%@",[user objectForKey:@"activity_details"]); NSLog(@"last_name:%@",[user objectForKey:@"last_name"]); NSLog(@"first_name:%@",[user objectForKey:@"first_name"]); NSLog(@"photo_url:%@",[user objectForKey:@"photo_url"]); } }
언급URL : https://stackoverflow.com/questions/5547311/how-do-i-parse-json-with-objective-c
반응형
'programing' 카테고리의 다른 글
Scala 2.10 + Json 시리얼화 및 디시리얼화 (0) | 2023.04.02 |
---|---|
C#에서 Oracle 스토어드 프로시저를 호출하시겠습니까? (0) | 2023.04.02 |
GridFS는 실전 가동에 충분한 속도와 신뢰성을 갖추고 있습니까? (0) | 2023.04.02 |
React TypeScript HoC - 컴포넌트를 프로펠러로 전달 (0) | 2023.04.02 |
jQuery를 사용하여 JSON 개체에 키가 있는지 확인합니다. (0) | 2023.04.02 |