c# - 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.
解决方案
创建一个类结构来匹配你的 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);
推荐阅读
- minikube - 我在哪里可以找到部署在 minikube 中的应用程序的主机 IP 地址
- c# - 触发时对象不使用 Sprite Renderer 出现
- java - 在Java中使用带有反应式包装器的非阻塞IO逐行读取文件
- java - 改造缓存的问题
- javascript - 如何在运行脚本之前检查 URL 中的特定单词?
- micropython - Micropython 继承失败
- codeigniter - 禁用先前使用 codeigniter 选择的下拉列表中的项目
- c# - SignalR 在 JQuery 3.x 中无法正常工作
- c# - 排序列表并返回原始索引
- c - 尝试根据排序的学生ID从文件中显示学生数据