user1994291
user1994291

Reputation:

Converting NSStrings to Json

I have search a lot ,i did found many answers, but not the specific one i need-which is so simple.

I want to take 2 different NSString that the user type, and create a json from them to send to server .

I wrote this :

-(id)stringToJason:(NSString*)stringData 
{
    NSData *data = [stringData dataUsingEncoding:NSUTF8StringEncoding];
    id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
    return json;
}

But there is something i dont get. this return 1 nsstring as json.

How would i take 2 different NSStrings, and create from them together ,the json ? Lets say: userName:me (when each one is comes from text field)

json should look like :

"Username": "me",
    "Firstname": "r",
    "Lastname": "k",

Upvotes: 1

Views: 1728

Answers (1)

Kitsune
Kitsune

Reputation: 9341

If you're wanting to produce JSON that looks like:

{
   "Username":"me",
   "Firstname":"r",
   "Lastname":"k"
}

Where r and k are values taken from the textfields, you could write a method along the lines of this:

-(NSData*)jsonFromFirstName:(NSString*)firstName andLastName:(NSString*)lastName
{
    NSDictionary* dic = @{@"Username" : @"me", @"Firstname" : firstName, @"Lastname" : lastName};
    // In production code, _check_for_errors!
    NSData* json = [NSJSONSerialization dataWithJSONObject:dic options:0 error:nil];
    return json;
}

You would call this method, passing the r (firstName) and k (lastName) values to it. It would construct a dictionary that has the structure of the desired JSON, with the desired values. You'd then use NSJSONSerialization's -dataWithJSONObject:options:error selector to convert the dictionary into a JSON data object (stored in an NSData object). You then have the data to send to the server!

The dictionary created in the first line of the method could be expanded as much as you desired, and you could even pass in non-strings (such as numbers, arrays, or even other dictionaries!).

Upvotes: 4

Related Questions