将Json对象转换为String - 目标C.

时间:2013-06-06 01:55:22

标签: objective-c json parsing object

想象一下,我向我的api发出请求,返回mysql_query("Select * from user where id=1")

请求完成后,它将在json中返回用户信息。 我做了一些调查,NSlog(@"JSON : %@",json);它给了我这个:

JSON : (
    {
    aboutme = "";
    active = 0;
    birthday = "1992-10-14";
    "city_id" = 0;
    email = "test@test.com";
    fbid = "";
    firstname = test;
    gender = 1;
    id = 162;
    lastname = test;
    password = "$2a$12$8iy.sGr.4V/Ea3GfHZe0m.SLDrvoSj3/wYRlWsNce1yyCMeCbDrMC";
    "phone_number" = "";
    "recovery_date" = "0000-00-00 00:00:00";
    "register_date" = "2013-06-06 02:44:20";
    salt = "8iy.sGr.4V/Ea3GfHZe0m";
    "user_type_id" = 1;
    username = test;
}
)

现在我用AFJONDecode解析它,当我得到[json valueForKey:@"username"];并调试它(NSlog(@"username = %@",[json valueForKey@"username"]);)时,我得到了这个:

username = (
    testeteste739
)

它给了我一个对象(因为在Json中,username = test而不是username =“test”)。

那么,我怎样才能将这个对象转换为字符串?

**更新**

我通过以下方式解决它:

NSArray *username = [JSON valueForKey:@"username"];
username = [username objectAtIndex:0];

有没有更好的方法来绕过这个? 感谢

1 个答案:

答案 0 :(得分:22)

由于JSON是一个字典对象,因此您可以将json数据转换为JSONDic NSDictionary变量并将其解析为字符串,如下所示: -

NSDictionary *JSONDic=[[NSDictionary alloc] init];
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:JSONDic
                                                   options:NSJSONWritingPrettyPrinted 
                                                     error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];