Reputation: 133
Converting NSString
to proper JSON format..
NSString *input_json = [NSString stringWithFormat:@"{\"id\":\"%@\",\"seconds\":\"%d\",\"buttons\": \"%@\"}", reco_id, interactionTime, json_Buttons];
Here json_Button
is in json format converted from nsdictionary..
My input_json result is:
{"id":"119","seconds":"10","buttons": "{ "update" : "2", "scan" : "4" }"}
It is not in a proper JSON format. key buttons contain "{}" I want to remove these quotes.
Expected Result is:
{ "id": "119", "seconds": "10", "buttons": { "update": "2", "scan": "4" } }
Upvotes: 1
Views: 201
Reputation: 318944
You are going about this all wrong. First, create an NSDictionary
that contains all of the data you want converted to JSON. Then use NSJSONSerialization
to properly convert the dictionary to JSON.
Something like this will work:
NSDictionary *dictionary = @{ @"id" : reco_id, @"seconds" : @(interactionTime), @"buttons" : json_Buttons };
NSError *error = nil;
NSData *data = [NSJSONSerialization dataWithJSONObject:dictionary options:NSJSONWritingPrettyPrinted error:&error];
if (data) {
NSString *jsonString = [[NSString alloc] intWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"JSON: %@", jsonString);
} else {
NSLog(@"Unable to convert dictionary to JSON: %@", error);
}
Upvotes: 2
Reputation: 131501
It's a bad idea to try to build JSON strings manually. Use the NSJSONSerialization class. That makes it easy. Create your dictionary, then call dataWithJSONObject:options:error:
.
If you use options: NSJSONWritingPrettyPrinted
it inserts line breaks and whitespace that makes the JSON more readable.
By using that function you get correctly formatted JSON every time, and it's flexible because if you send it a different dictionary you get different JSON.
Upvotes: 0