2012-09-28 150 views
-2
陣列

可能重複:
Best JSON library to use when developing an iPhone application?轉換一個NSDictionary對象到對象

我有以下在JSON結構,而我發送請求:

[ 
    { 
     "uid": "20", 
     "count": "4" 
    }, 
    { 
     "uid": "48", 
     "count": "0" 
    }, 
    { 
     "uid": "49", 
     "count": "0" 
    }, 
    { 
     "uid": "53", 
     "count": "0" 
    } 
] 
And I want to get the following structure : 
[ 
    { 
     "uid": "53", 
     "count": "0" 
    } 
] 

Using sender.tag I am able to get the following structure in the NSDictionary *json object, something like the following: 
{ 

"uid": "53", 

"count": "0" 
} 

我也想要方括號(對象數組)。 請告訴我如何將此NSDictionary對象轉換爲對象數組。

+0

檢查。有很多重複的問題可以在SO – akk

+0

中找到。他沒有使用JSON。他只是將'NSDictionary'顯示爲JSON。這是一個很大的區別。 –

回答

0

得到字典後(比如:字典)

嘗試以下操作:

NSMutableString *str = [[NSMutableString alloc]init]; 

    for (id keys in dict) { 

     NSString *strKey = [NSString stringWithFormat:@"\" %@ \":",keys]; 
     [str appendString:strKey]; 

     NSString *strKeyValue = [NSString stringWithFormat:@"\" %@ \",",[dict valueForKey: keys]]; 
     [str appendString:strKeyValue]; 

    } 

    NSString *jsonString = [NSString stringWithFormat:@"[{%@}]",[str substringToIndex:[str length]-1] ]; 

    NSLog(@"jsonString is %@",jsonString); 
    NSData *data = [jsonString dataUsingEncoding:NSUTF8StringEncoding]; 

    NSArray *a = [[NSArray alloc]init]; 

    a =(NSArray *) [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil]; 
    NSLog(@"decoded array is %@",a);