Converting Json Object to String - Objective C

17,711

As JSON is a dictionary object, so you can get your json data to JSONDic NSDictionary variable and parse it to string as follows:-

NSDictionary *JSONDic=[[NSDictionary alloc] init];
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:JSONDic
                                                   options:NSJSONWritingPrettyPrinted 
                                                     error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
Share:
17,711
Tiago Almeida
Author by

Tiago Almeida

Updated on July 07, 2022

Comments

  • Tiago Almeida
    Tiago Almeida almost 2 years

    Imagine I make an request to my api that return an mysql_query("Select * from user where id=1").

    After the request is done, it returns the user info in json. I do some debuging, NSlog(@"JSON : %@",json); and it gives me this:

    JSON : (
        {
        aboutme = "";
        active = 0;
        birthday = "1992-10-14";
        "city_id" = 0;
        email = "[email protected]";
        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;
    }
    )
    

    Now I parse it with AFJONDecode and when I get the [json valueForKey:@"username"]; and debug it ( NSlog(@"username = %@",[json valueForKey@"username"]); ) and I get this:

    username = (
        testeteste739
    )
    

    It gives me an object ( because in the Json, the username = test and not username = "test").

    So, how can i convert this object to string?

    ** UPDATE **

    I resolve it by the following way:

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

    Is there any better way to overpass this? Thanks

  • Hot Licks
    Hot Licks almost 11 years
    That is, of course, the way to create a JSON string, given an internal representation in NSArray/NSDictionary objects. (Hopefully your JSONDict object has contents when you actually do this.) I think the OP is still struggling to get values OUT of the JSON.
  • Prince Kumar Sharma
    Prince Kumar Sharma almost 11 years
    As question title specifies the he want to convert JSON to string I did this , he didn't specify in the title that he want values out of JSON.
  • Hot Licks
    Hot Licks almost 11 years
    He doesn't know what he wants.
  • Tiago Almeida
    Tiago Almeida almost 11 years
    All i wanted was to get the value "username". I already resolve it, so thanks everyone and sorry for all my confusion!