JSON data in PUT request in C#

1.9k views Asked by At

I am trying to make a PUT request with a C# client, this request has JSON data in it.

I use this, which I got from here: Passing values to a PUT JSON Request in C#

var serializer = new JavaScriptSerializer();
string json = serializer.Serialize(new 
{
    reg_FirstName = "Bob",
    reg_LastName = "The Guy"
});

Ofcourse, the Json string looks like this:

  {
    "reg_FirstName":"Bob",
    "reg_LastName":"The Guy"
  }

But how would I go around creating a JSON string like this:

  {
    "main": {
        "reg_FirstName": "Bob",
        "reg_LastName": "The Guy"
    },
    "others": [
        {
            "reg_FirstName": "Robert",
            "reg_LastName": "The Guy"
        },
        {
            "reg_FirstName": "Rob",
            "reg_LastName": "The Guy"
        }
    ]
}
1

There are 1 answers

0
b2zw2a On BEST ANSWER

You can use the same way - dynamic objects, so in your case it would look like this:

var serializer = new JavaScriptSerializer();
string json =
    serializer.Serialize(
        new {
            main = new
            {
                reg_FirstName = "Bob", 
                reg_LastName = "The Guy"
            },
            others = new[]
            {
                new { reg_FirstName = "Bob", reg_LastName = "The Guy" }, 
                new { reg_FirstName = "Bob", reg_LastName = "The Guy" }
            }
        }
    );