I'm trying to post two fields and a bundled object with two fields to Mailchimp's API endpoint.
var store_id = ConfigurationManager.AppSettings["MailChimpStoreID"];
var method = String.Format("ecommerce/stores/{0}/products?", store_id);
var id = "id123";
var title = "testproduct";
//var variants = new {id, title };
var productData = new { id, title, variants = new { id, title } };
var requestJson = JsonConvert.SerializeObject(productData);
When I POST my data and do a try-catch around my code to check, I see that my requestJson returns the following:
{
"id":"id123",
"title":"testproduct",
"variants":{"id":"id123","title":"testproduct"}
}
I know the issue is that the variants when serialized isn't returning as "variants":[{"foo":bar"}]
but how do I resolve it so that my code bundles this as an object correctly?
Second theory: Since C# is a strongly-typed Object Oriented program, do I need to define the objects above with get:sets and then call them into my function?
you should write it like this,
var productData = new { id, title, variants = new[] {new { id, title }} };
Console.WriteLine(JsonConvert.SerializeObject(productData));
//Prints:
{"id":1,"title":"sodijf","variants":[{"id":1,"title":"sodijf"}]}
You can use either dynamic
or an object
as the type of list as well.
var productData = new { id, title, variants = new List<object>() {new { id, title }} };