2011-12-27 98 views
0
{ 
"id": "1", 
"result": [ 
{ 
"Name": "John", 
"Statu": "Online" 
}, 
{ 
"Name": "Alex", 
"Statu": "Online" 
}, 
{ 
"Name": "Diaz", 
"Statu": "Offline" 
} 
] 
} 

我如何提取每一個「車」的JSON對象,並把它變成一個本地對象?我嘗試了幾種方法,但我不能那樣做。如何將Json請求轉換爲本地對象或列表?

NSString *responseString = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease]; 

     NSString *responseDict = [responseString JSONValue]; 

     NSArray *objects = [NSArray arrayWithObjects:[responseDict valueForKeyPath:@"result.Name"],[responseDict valueForKeyPath:@"result.Statu"],nil]; 
     NSLog(@"objects Array: %@",objects); 



    **==> NSLOG gives: 
         (
         (
         "John", 
         "Alex", 
         "Diaz" 
         ), 
         (
         "Online", 
         "Online", 
         "Offline" 
         ) 
        ) 



    NSArray *resultsArray = [responseString JSONValue]; 

    for (NSDictionary *personDict in resultsArray) 
     { 

     NSLog(@"ihaleAdi =: %@",[carDict valueForKey:@"result.ihaleAdi"]); 

     NSLog(@"ihaleDurum =: %@",[carDict valueForKey:@"result.Statu"]); 

     } 

但是我得到一個錯誤我想只是推薦他們但我不能做任何人可以幫助我嗎?感謝您閱讀

回答

1

使用數組來捕獲responseString:

NSString *responseString = [request responseString]; 
NSArray *array = [responseString JSONValue]; 

然後,當你需要從陣列中的個別項目使用詞典:

// 0 is the index of the array you need 
NSDictionary *itemDictionary = (NSDictionary *)[array objectAtIndex:0]; 

給出一個JSON responseString看起來像這樣:

[{「UniqueID」:111111,「DeviceName」:「DeviceName1」,「Location」:「Device1Loc」,「Description」:「Device1Desc」},{「UniqueID」:22222, :「設備名稱2" , 「位置」: 「Device2Loc」, 「說明」: 「Device2Desc」}]

你會風與看起來像這樣的數組:

myArray = (
     { 
     Description = "Device1Desc"; 
     DeviceName = "DeviceName1"; 
     Location = "Device1Loc"; 
     UniqueID = 111111; 
    }, 
     { 
     Description = "Device2Desc"; 
     DeviceName = "DeviceName2"; 
     Location = "Device2Loc"; 
     UniqueID = 222222; 
    } 
) 

和索引0的字典,看起來像這樣:

myDictionary = { 
    Description = "Device1Desc"; 
    DeviceName = "DeviceName1"; 
    Location = "Device1Loc"; 
    UniqueID = 111111; 
} 

對不起,以前的任何混淆和不適當實例化的對象。我仍然是一個相對的新手,今天學到了一些東西。

+0

頂行(NSString * responseString = [request responseString];)假定您正在使用ASIHttpRequest委託方法。如果您以其他方式實例化請求對象,請忽略該行。 –

+0

第二行創建一個被JSONValue覆蓋的數組。你已經泄露了它。 – Abizern

+0

它給出了一個錯誤,如:[__NSCFDictionary objectAtIndex:]:無法識別的選擇發送到實例0x6b43300 – user1117361