2

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?

kzone95
  • 49
  • 6
  • 2
    Make it a list if you expect [ ] – Jawad Jul 08 '20 at 00:12
  • 2
    Do you want it to be `"variants":[{"foo":bar"}]`? If so, do something like `var productData = new { id, title, variants = new [] { new { id, title } } };`. The brackets represent a collection (/array). To get them, you need a collection or an array of objects (which is what `new [] { }` gives you. – Flydog57 Jul 08 '20 at 00:14

1 Answers1

2

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 }} };
Jawad
  • 11,028
  • 3
  • 24
  • 37