首页 > 解决方案 > 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.

标签: c#jsonpost

解决方案


创建一个类结构来匹配你的 json,

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

使用 JsonConvert 或任何其他方法序列化数据。

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

假设您已经将序列化数据注入到您的类中,则使用 httpclient 发布序列化数据。

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

推荐阅读