Search code examples
objective-cjsonnsdatansmutabledictionary

convert NSMutableDictionary to JSON and string


I want to add a json data to HTTPBody request for an iOS app. I am using objective c. So I decided to use NSMutableDictionary to convert it to JSON @property NSMutableDictionary* project;

Parameters: project (required): a hash of the project attributes, including: name (required): the project name identifier (required): the project identifier description This is the JSON format when adding data as a raw: If I want the JSON to look like this, do I have to create NSMutableDictionary object and have another NSMutableDictionary object inside it with the key name @"project"?

{
    "project": {
        "name": "",
        "identifier": "example",
        "description": "",
    }
}

I tried to have only one NSMutableDictionary Here is my code:

[self.project setObject:self.projectName.text forKey:@"name"];
[self.project setObject:self.projectDescription.text forKey:@"description"];
[self.project setObject:self.projectIdentifier.text forKey:@"identifier"];

Here is how to convert it to JSON:

NSData *data = [NSJSONSerialization dataWithJSONObject:project options:NSJSONWritingPrettyPrinted error:nil];
    NSString* jsonString = [[NSString alloc]initWithData: data
                                              encoding: NSUTF8StringEncoding ];
NSData* anotherdataobj = jsonString;
    [request setHTTPBody:anotherdataobj];

I convert it to NSData again because HTTPBody accept NSData for the parameter.

To be clear: 1- do i have to create NSMutableDictionary for project and add NSMutableDictionary projectdetails as a value for for its key @"project" 2- Do I have to convert the string into NSData again to pass it for the HTTPBody? Correct me if i'm wrong here?


Solution

  • You will definitely need another dictionary inside the first one. Whether you use a mutable version or a literal is up to you.

    Note: you probably want to use the newer and much more readable Objective-C syntax.

    Option 1:

    NSMutableDictionary *object = [NSMutableDictionary dictionary];
    NSMutableDictionary *project = [NSMutableDictionary dictionary];
    project[@"name"] = whatever;
    project[@"identifier"] = whateverElse;
    project[@"description"] = stillSomethingElse;
    object[@"project"] = project;
    

    Option 2:

    NSDictionary *object =
    @{
        @"project":
        @{
            @"name": whatever,
            @"identifier": whateverElse,
            @"description": stillSomethingElse,
        }
    };
    

    NSJSONSerialization dataWithJSONObject:options:error: already returns an NSData object? Why would you need to convert it again? Also, you certainly don't want to cast an NSData object to an NSString, they're two completely different objects.