Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting Json Object to String - Objective C

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

like image 952
Tiago Almeida Avatar asked Jun 06 '13 01:06

Tiago Almeida


People also ask

How to convert JSONobject into string?

Use the JavaScript function JSON.stringify() to convert it into a string. const myJSON = JSON.stringify(obj); The result will be a string following the JSON notation.

What is a JSON stringify() used for?

The JSON.stringify() method converts a JavaScript value to a JSON string, optionally replacing values if a replacer function is specified or optionally including only the specified properties if a replacer array is specified.

How to use JSON string in JavaScript?

Example - Parsing JSONUse the JavaScript function JSON.parse() to convert text into a JavaScript object: const obj = JSON.parse('{"name":"John", "age":30, "city":"New York"}'); Make sure the text is in JSON format, or else you will get a syntax error.


1 Answers

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];
like image 71
Prince Kumar Sharma Avatar answered Oct 01 '22 09:10

Prince Kumar Sharma