3

I have some data in JSON format that I need to send to a web address via a POST request. The data resembles the following example:

[
 {
  "Id":0,
  "Name":"John"
 },
 {
  "Id":0,
  "Name": "James"
 }
]

I would normally have no problem uploading the data as a NameValueCollection using the WebClient.UploadValues() method:

using (WebClient Client = InitWebClient()) // InitWebClient() initialises a new WebClient and sets the BaseAddress and Encoding properties
{
    NameValueCollection Values = new NameValueCollection
    {
        {"Id", "0"},
        {"Name", "John"}
    };
    Client.UploadValues("/api/example", "POST", Values);                
}

However as this JSON request is a list (and must always be in the form of a list even if there is only one item being uploaded) I am at a loss as to how this is done.

Due to programming constraints I need to do all of this using the WebClient object.

Conor McCauley
  • 125
  • 1
  • 2
  • 16
  • 3
    Possible duplicate of [POSTing JSON to URL via WebClient in C#](https://stackoverflow.com/questions/15091300/posting-json-to-url-via-webclient-in-c-sharp) – croxy Aug 22 '18 at 10:43

1 Answers1

-3

Someone answered this question already but their answer was removed for some reason. Their solution was valid, however, so I've thrown together a rough implementation of it below (it's not at all dynamic but it should help others who have a problem similar to mine):

using (WebClient Client = InitWebClient())
{

    List<MyJsonObject> Items = new List<MyJsonObject>();

    // The following could easily be made into a for loop, etc:
    MyJsonObject Item1 = new MyJsonObject() {
        Id = 0,
        Name = "John"
    };
    Items.Add(Item1);
    MyJsonObject Item2 = new MyJsonObject() {
        Id = 1,
        Name = "James"
    };
    Items.Add(Item2);

    string Json = Newtonsoft.Json.JsonConvert.SerializeObject(Items)
    Client.Headers[HttpRequestHeader.ContentType] = "application/json";
    Client.UploadValues("/api/example", "POST", Json);

}

Here is the object that will be serialized:

public class MyJsonObject {
    public int Id { get; set; }
    public string Name { get; set; }
}
Conor McCauley
  • 125
  • 1
  • 2
  • 16