2

如何使用 NSJSONSerialization 转换此 json?

{
   "messages":{
      "message":{
         "user":"value",
         "pass":"value",
         "url":"value"
      }
   }
}
4

2 回答 2

5
NSError* error;
NSDictionary *dit = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:&error];
if (!error) {
   //Get values from this dict using respective keys
   NSDictionary *msgs = [dict objectForKey:@"messages"];
   NSDictionary *msg = [msgs objectForKey:@"message"];
   NSString *user = [msg objectForKey:@"user"];
   NSString *pass = [msg objectForKey:@"pass"];
   NSString *url = [msg objectForKey:@"url"];
}
else {
   //Your error message
}
于 2012-12-14T16:19:01.973 回答
1

使用新文字语法的示例:

char *jsonChars = "{\
    \"messages\":{\
        \"message\":{\
            \"user\":\"value\",\
            \"pass\":\"value\",\
            \"url\":\"value\"\
        }\
    }\
}";

NSData *responseData = [NSData dataWithBytes:jsonChars length:strlen(jsonChars)];
NSError* error;
NSDictionary *dit = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:&error];
NSLog(@"dit: %@", dit);
NSLog(@"dit: messages:message:user = %@", dit[@"messages"][@"message"][@"user"]);

NSLog 输出:

滴答:{消息={消息={通过=值;网址=价值;用户=价值;}; }; }

dit:消息:消息:用户 = 值

于 2012-12-14T17:18:56.667 回答