简体   繁体   中英

C# POST request with Json containing an array

I have been using some simple requests in past to send JSON and they have been working fine. I basically take simple string, convert it to UTF-8 using
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
and send this using HttpWebRequest.

Now I have received a task to send a new POST request which will have an array of Ids and be of type

{
    "GroupID": "Named_ID",
    "ChildIds": [
        "76197272-24E4-4DD2-90B8-46FDDCC0D6CA",
        "D2B3A1AC-ACF6-EA11-A815-000D3A49E4F3",
        "ED53D968-00F4-EA11-A815-000D3A49E4F3"
    ]
}

The ChildIds are available in a List(String []) with me. I could loop through the records and create a similar long string and then convert to byteArray in UTF8 but I feel this can be done in a simpler way. Examples that I have seen on the forum of using array in JSON always appear to use JsonConvert.SerializeObject but I am not clear if I should use this and if I do then do I convert the serialised object to UTF8 like I did earlier and is it then ok to use in the HttpWebRequest. Can someone please advice on the approach I should take.

Create a class structure to match your json,

public class Data
{
    public string GroupId {get;set;} 
    public List<string> ChildIds {get;set;} 
} 

serialize the data with JsonConvert or any other.

var json = JsonConvert.SerializeObject<Data>(str) ;

Post the serialized data with httpclient assuming you have it injected in your class already.

var data = new StringContent(json, Encoding.UTF8, "application/json");
var post = await client.PostAsync(url, data);

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