Reputation: 8609
I am attempting to create json data to send to a server via an HTTP POST request. The server will only accept a specific format of JSON, otherwise it will return an error. I can successfully create and upload the JSON file to the server, however I am getting the following error because I have not formatted my JSON incorrectly:
JSON Error Message: {
code = "-2";
message = "Validation error: {\"message\":{\"to\":[\"Please enter an array\"]}}";
name = ValidationError;
status = error;
}
As you can see, the server needs a complex JSON format with an Array of Values and Keys but I'm not sure how to do that. Below is my current code to create the JSON data:
//Create Array With TO Values
NSDictionary *toField = @{@"email" : emailField.text};
//Create Dictionary Values
NSDictionary *messageContent = @{@"subject" : @"APPNAME Registration Complete", @"from_email" : @"[email protected]", @"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];
According to the server, I need an array with keys and values, similar to a nsdictionary. When I use an NSArray, though, I can't add values / keys. Any ideas on how I should go about doing this? Below is an example of the JSON format that the server will accept, am I doing everything right to follow this format? If not, what do I need to change to match the format?
{
"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": "[email protected]",
"from_name": "example from_name",
"to": [
{
"email": "example email",
"name": "example name"
}
],
}}
Upvotes: 1
Views: 2394
Reputation: 14304
Looks like the "to" field expects an array. Unless the variable toField
is an NSArray that contains dictionaries with keys and values as described, you're going to get a JSON that's not exactly like the one you want.
I would suggest outputting the description of the outgoing JSON to see exactly where there are differences.
Update I saw the addition to your question -
NSDictionary *toField = @{@"email" : emailField.text};
Does not create an array. Try:
NSArray *toField = @[@{@"email" : emailField.text}];
Upvotes: 3