将 NSMutableDictionary 转换为 JSON 和字符串

convert NSMutableDictionary to JSON and string

我想将 json 数据添加到 iOS 应用程序的 HTTPBody 请求中。 我正在使用 objective c。 所以我决定使用 NSMutableDictionary 将其转换为 JSON @属性 NSMutableDictionary* 项目;

参数: 项目(必填):项目属性的散列,包括: 名称(必填):项目名称 标识符(必需):项目标识符 描述 这是添加原始数据时的 JSON 格式: 如果我希望 JSON 看起来像这样,我是否必须创建 NSMutableDictionary 对象并在其中包含另一个 NSMutableDictionary 对象,其键名为 @"project"?

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

我试过只有一个NSMutableDictionary 这是我的代码:

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

以下是将其转换为 JSON 的方法:

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

我再次将其转换为 NSData,因为 HTTPBody 接受 NSData 作为参数。

明确一点: 1- 我是否必须为项目创建 NSMutableDictionary 并添加 NSMutableDictionary projectdetails 作为其键 @"project" 的值 2- 我是否必须再次将字符串转换为 NSData 才能将其传递给 HTTPBody? 如果我在这里错了,请纠正我?

您肯定需要在第一本词典中再添加一本词典。使用可变版本还是文字由您决定。

注意:您可能希望使用更新且更易读的 Objective-C 语法。

选项 1:

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

选项 2:

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

NSJSONSerialization dataWithJSONObject:options:error: 已经 returns 一个 NSData 对象?为什么你需要再次转换它?此外,您当然不想将 NSData 对象转换为 NSString,它们是两个完全不同的对象。