如何将List<PostClass>作为参数序列化后发送至API接口?
如何在POST请求中序列化并发送List类型参数
当前运行正常的模型与代码:
public class PostClass { public string VariantName { get; set; } public string VariantNames { get; set; } } HttpWebRequest httpWebRequestContent = (HttpWebRequest)WebRequest.Create("https://localhost:44000/api/Variant/Example"); httpWebRequestContent.ContentType = "application/json"; httpWebRequestContent.Accept = "application/json"; httpWebRequestContent.PreAuthenticate = true; httpWebRequestContent.Method = "POST"; using (StreamWriter streamWriterContent = new StreamWriter(httpWebRequestContent.GetRequestStream())) { string json = JsonConvert.SerializeObject(new { VariantName = model.VariantName, VariantDetailNames = model.VariantDetailNames }); streamWriterContent.Write(json); }
需求:
需要将List<PostClass> modelList这个列表作为参数通过序列化发送到接口。
修改方案:
直接把modelList传入JsonConvert.SerializeObject即可,Json.NET会自动将列表序列化为标准JSON数组格式。修改后的核心代码如下:
// 请求初始化部分保持不变 HttpWebRequest httpWebRequestContent = (HttpWebRequest)WebRequest.Create("https://localhost:44000/api/Variant/Example"); httpWebRequestContent.ContentType = "application/json"; httpWebRequestContent.Accept = "application/json"; httpWebRequestContent.PreAuthenticate = true; httpWebRequestContent.Method = "POST"; using (StreamWriter streamWriterContent = new StreamWriter(httpWebRequestContent.GetRequestStream())) { // 直接序列化List<PostClass>对象 string json = JsonConvert.SerializeObject(modelList); streamWriterContent.Write(json); }
补充说明:
如果后端接口要求参数是嵌套在某个对象中的列表(而非直接接收数组),则需要调整序列化的结构,示例如下:
string json = JsonConvert.SerializeObject(new { VariantList = modelList // 属性名需与后端接口接收的参数名完全一致 });
内容的提问来源于stack exchange,提问作者Yunus Mert Çakar
相关产品推荐
相关产品推荐

