如何在C#中存储POST请求JSON Body并替换自定义参数变量
C# 构造可替换参数的API请求JSON Body实现方案
方案1:强类型模型序列化(推荐,类型安全无转义风险)
首先定义和目标JSON结构匹配的C#类:
// 对应records数组里的attributes字段 public class Attributes { public string type { get; set; } = "Case"; } // 对应records数组的元素 public class Record { public Attributes attributes { get; set; } = new(); public string Id { get; set; } public string Comment__c { get; set; } } // 对应整个JSON根结构 public class CaseUpdateRequest { public bool allOrNone { get; set; } = false; public List<Record> records { get; set; } = new(); }
之后直接给属性赋值再序列化即可,可灵活替换变量:
// 你的自定义变量 string customId = "你的实际Id值"; string customComment = "你的实际评论内容"; // 构造请求对象 var requestObj = new CaseUpdateRequest { records = new List<Record> { new Record { Id = customId, Comment__c = customComment } } }; // 序列化得到JSON字符串(.NET 自带System.Text.Json实现) string jsonBody = System.Text.Json.JsonSerializer.Serialize(requestObj); // 如果用Newtonsoft.Json,序列化代码为: // string jsonBody = Newtonsoft.Json.JsonConvert.SerializeObject(requestObj);
方案2:动态构造JSON(适合轻量场景,无需预定义类)
如果不想单独定义类,可以用JSON动态操作类实现:
基于System.Text.Json(.NET 6+支持)
string customId = "你的实际Id值"; string customComment = "你的实际评论内容"; // 构造JSON对象 var jsonObj = new System.Text.Json.Nodes.JsonObject { ["allOrNone"] = false, ["records"] = new System.Text.Json.Nodes.JsonArray { new System.Text.Json.Nodes.JsonObject { ["attributes"] = new System.Text.Json.Nodes.JsonObject { ["type"] = "Case" }, ["Id"] = customId, ["Comment__c"] = customComment } } }; // 转JSON字符串 string jsonBody = jsonObj.ToJsonString();
基于Newtonsoft.Json
string customId = "你的实际Id值"; string customComment = "你的实际评论内容"; var jsonObj = new Newtonsoft.Json.Linq.JObject { ["allOrNone"] = false, ["records"] = new Newtonsoft.Json.Linq.JArray { new Newtonsoft.Json.Linq.JObject { ["attributes"] = new Newtonsoft.Json.Linq.JObject { ["type"] = "Case" }, ["Id"] = customId, ["Comment__c"] = customComment } } }; string jsonBody = jsonObj.ToString();
注意事项
- 不要直接用字符串拼接的方式替换JSON参数,避免评论内容含特殊字符(比如引号、换行)时JSON结构被破坏
- 序列化后的jsonBody可以直接放入HTTP请求的Body中调用接口
内容的提问来源于stack exchange,提问作者Akshay
相关产品推荐
相关产品推荐

