1

This is the json coming from the server:

{
    "name":"channelname",   
    "args":
    [
        {           
            "username":"myusername",
            "message":"mymessage"
        }
    ]
} 

Using ios5 built-in json methods I try to parse out the args's username/message.

NSDictionary *JSON = [NSJSONSerialization JSONObjectWithData: [packet.data dataUsingEncoding:NSUTF8StringEncoding] options: NSJSONReadingMutableContainers error: nil];
NSDictionary *argsValues = [[NSDictionary alloc] initWithDictionary:[JSON objectForKey:@"args"]];

Second line throws an error:

dictionary argument is not an NSDictionary

When I NSlog [JSON objectForKey@"args"] I get:

(
    {
        message = mymessage;
        username = myusername;
    }
)

I think the parenthesis are breaking it, don't know where they came from, help appreciated.

EDIT:

Thanks to chosen answer, here's the code I used to get the args keys.

NSDictionary *JSON = [NSJSONSerialization JSONObjectWithData: [packet.data dataUsingEncoding:NSUTF8StringEncoding] options: NSJSONReadingMutableLeaves error: nil];
NSArray *argsArray = [[NSArray alloc] initWithArray:[JSON objectForKey:@"args"]];
NSDictionary *argsDict = [[NSDictionary alloc] initWithDictionary:[argsArray objectAtIndex:0]];
NSLog(@"keys = %@", [argsDict allKeys]);
4

1 回答 1

2
[json objectForKey:@"args"]

是一个 NSArray。您不能直接使用数组初始化 NSDictionary。

(在 JSON 中,{ 和 } 表示键值对,如 NSDictionary,而 [ 和 ] 分隔有序列表,如 NSArray,这就是映射按原样完成的原因......)

于 2012-06-30T23:42:32.627 回答