简体   繁体   中英

C# WebClient upload JSON in POST request

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.

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; }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM