使用带有数组的NSDictionary创建JSON文件



我正试图创建json数据,通过HTTPPOST请求发送到服务器。服务器将只接受特定格式的JSON,否则将返回错误。我可以成功地创建JSON文件并将其上传到服务器,但我收到了以下错误,因为我没有错误地格式化JSON:

JSON Error Message: {
    code = "-2";
    message = "Validation error: {"message":{"to":["Please enter an array"]}}";
    name = ValidationError;
    status = error;
}

正如您所看到的,服务器需要一个包含值和键数组的复杂JSON格式,但我不知道如何做到这一点。以下是我当前创建JSON数据的代码:

//Create Array With TO Values
NSDictionary *toField = @{@"email" : emailField.text};
//Create Dictionary Values                
NSDictionary *messageContent = @{@"subject" : @"APPNAME Registration Complete", @"from_email" : @"email@domain.com", @"to" : toField};
NSDictionary *mandrillValues = @{@"key" : @"APPKEY",
                                 @"redirect_url" : @"PRIVATE-URL",
                                 @"template_name" : @"app-registration",
                                 @"template_content" : [NSNull null],
                                 @"message" : messageContent
                                };
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:mandrillValues options:NSJSONWritingPrettyPrinted error:nil];

根据服务器,我需要一个包含键和值的数组,类似于nsdictionary不过,当我使用NSArray时,我不能添加值/键。我该怎么做有什么想法吗下面是服务器将接受的JSON格式的示例,我是否按照这种格式做了所有正确的事情?如果没有,我需要更改什么以匹配格式?

{
"key": "example key",
"template_name": "example template_name",
"template_content": [
    {
        "name": "example name",
        "content": "example content"
    }
],
"message": {
    "text": "example text",
    "subject": "example subject",
    "from_email": "message.from_email@example.com",
    "from_name": "example from_name",
    "to": [
        {
            "email": "example email",
            "name": "example name"
        }
    ],
}}

看起来"to"字段需要一个数组。除非变量toField是一个NSArray,它包含具有所述键和值的字典,否则您将得到一个与您想要的不完全相同的JSON。

我建议输出输出JSON的描述,以查看到底哪里存在差异。

更新我看到你的问题增加了

NSDictionary *toField = @{@"email" : emailField.text};

不创建数组。尝试:

NSArray *toField = @[@{@"email" : emailField.text}];

最新更新