You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将C#数据模型以原始JSON格式正确发送?

解决RestSharp发送原始JSON格式错误的问题

我懂你这种头疼的感觉——明明在Postman里能发对的JSON,换成RestSharp就格式乱了。咱们来一步步搞定它,分两种场景给你解决方案:

场景1:用C#模型生成正确的JSON

如果你的数据是用C#类定义的,首先要确保模型结构和目标JSON完全对应。比如Postman里的正确JSON是:

{
"userName": "Alice",
"contactInfo": {
"email": "alice@example.com",
"phone": "1234567890"
},
"isActive": true
}

那对应的C#模型得这么定义:

using System.Text.Json.Serialization;

public class ContactInfo
{
    [JsonPropertyName("email")]
    public string Email { get; set; }
    
    [JsonPropertyName("phone")]
    public string Phone { get; set; }
}

public class UserRequest
{
    [JsonPropertyName("userName")] // 用JsonPropertyName确保属性名和JSON键完全匹配
    public string UserName { get; set; }
    
    [JsonPropertyName("contactInfo")]
    public ContactInfo ContactInfo { get; set; }
    
    [JsonPropertyName("isActive")]
    public bool IsActive { get; set; }
}

然后用RestSharp发送的时候,要正确配置序列化逻辑(这里用RestSharp v107+的最新API写法,更简洁可靠):

// 初始化RestClient,指定API基础地址
var client = new RestClient("https://your-api-domain.com");

// 填充模型数据
var requestModel = new UserRequest
{
    UserName = "Alice",
    ContactInfo = new ContactInfo
    {
        Email = "alice@example.com",
        Phone = "1234567890"
    },
    IsActive = true
};

// 创建POST请求,指定接口路径
var request = new RestRequest("/api/users", Method.Post);

// 关键:用AddJsonBody方法添加模型,RestSharp会自动序列化为标准JSON
request.AddJsonBody(requestModel);

// 发送请求并获取响应
var response = await client.ExecuteAsync(request);

场景2:直接发送原始JSON字符串

如果你不想用模型,或者需要完全自定义JSON内容,可以直接发送原始字符串:

var client = new RestClient("https://your-api-domain.com");
var request = new RestRequest("/api/users", Method.Post);

// 复制Postman里的正确JSON字符串(注意转义双引号)
var rawJson = @"
{
    ""userName"": ""Alice"",
    ""contactInfo"": {
        ""email"": ""alice@example.com"",
        ""phone"": ""1234567890""
    },
    ""isActive"": true
}";

// 添加原始JSON,明确指定媒体类型为application/json
request.AddStringBody(rawJson, ContentType.Json);

var response = await client.ExecuteAsync(request);

常见错误排查

  • 检查ContentType是否正确:RestSharp的AddJsonBody会自动设置application/json,但如果手动配置,别误设成application/x-www-form-urlencoded
  • 模型属性名和JSON键不匹配:一定要用JsonPropertyName(System.Text.Json)或JsonProperty(Newtonsoft.Json)做映射,避免大小写或名称不一致的问题
  • 旧版本RestSharp的坑:如果用v106及以下版本,需要手动安装RestSharp.NewtonsoftJson包并配置序列化器:
    var client = new RestClient();
    client.UseNewtonsoftJson();
    

这样调整后,发送的JSON格式就和Postman里的完全一致了!

内容的提问来源于stack exchange,提问作者user9377278

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 09:32:27