2012-09-28 247 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);