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

使用RestSharp 110.2.0与.NET7时AddJsonBody无法提交含字符串列表的对象

RestSharp 110.2.0 AddJsonBody提交含字符串列表对象失败的解决办法

问题场景

在.NET 7环境下使用RestSharp 110.2.0组件时,通过AddStringBody提交JSON格式字符串能正常调用接口,但使用AddJsonBody提交包含字符串列表的对象时请求失败。已通过Talend API Tester验证过以下请求体格式是有效的:

{
  "ApiRequest": {
    "TransactionId": "1234",
    "Version":"",
    "TestGUIDs": ["c1c1ee44-6ae1-485b-bb4e-8ca4a4837830"]
  }
}

有效代码(字符串提交)

string stringBody = @"
    {
      ""ApiRequest"": {
        ""TransactionId"": ""1234"",
        ""Version"":"""",
        ""TestGUIDs"": [""c1c1ee44-6ae1-485b-bb4e-8ca4a4837830""]
      }
    }";

restRequest.AddStringBody(stringBody, ContentType.Json);

无效代码(对象提交)

QGRequest qGRequest = new QGRequest
{
    ApiRequest = new ApiRequest
    {
        TransactionId = "1234",
        Version = "",
        TestGUIDs = new List<string> { "c1c1ee44-6ae1-485b-bb4e-8ca4a4837830" }
    }
};

restRequest.AddJsonBody(qGRequest);

问题原因

RestSharp 107及以上版本默认使用System.Text.Json进行序列化,而旧版本依赖Newtonsoft.Json。如果实体类未配置正确的序列化属性,或者System.Text.Json的默认行为(如属性命名策略、空值处理)与接口要求的格式不匹配,就会导致序列化后的JSON不符合接口预期,进而请求失败。

解决方案

1. 配置System.Text.Json序列化选项

显式指定序列化规则,确保生成的JSON和验证通过的格式一致:

var jsonOptions = new JsonSerializerOptions
{
    PropertyNamingPolicy = null, // 保持属性原命名(PascalCase),如果接口要求小驼峰则改为 JsonNamingPolicy.CamelCase
    WriteIndented = true, // 可选,和字符串版本格式对齐
    DefaultIgnoreCondition = JsonIgnoreCondition.Never // 确保空字符串不会被忽略
};

restRequest.AddJsonBody(qGRequest, jsonOptions);

2. 给实体类添加序列化属性

通过JsonPropertyName特性强制指定JSON键名,避免命名策略差异:

using System.Text.Json.Serialization;

public class QGRequest
{
    [JsonPropertyName("ApiRequest")]
    public ApiRequest ApiRequest { get; set; }
}

public class ApiRequest
{
    [JsonPropertyName("TransactionId")]
    public string TransactionId { get; set; }
    
    [JsonPropertyName("Version")]
    public string Version { get; set; }
    
    [JsonPropertyName("TestGUIDs")]
    public List<string> TestGUIDs { get; set; }
}

3. 切换为Newtonsoft.Json序列化

如果System.Text.Json的行为不符合需求,可配置RestSharp使用Newtonsoft.Json:

  1. 安装NuGet包:RestSharp.Serializers.NewtonsoftJson
  2. 初始化RestClient时指定序列化器:
var client = new RestClient("你的接口基础地址", configureSerialization: s => s.UseNewtonsoftJson());

4. 验证序列化结果

先将对象序列化为字符串,对比正确的JSON格式,排查差异:

// 用System.Text.Json序列化
var serializedJson = JsonSerializer.Serialize(qGRequest);
// 或者用Newtonsoft.Json
// var serializedJson = Newtonsoft.Json.JsonConvert.SerializeObject(qGRequest);
Console.WriteLine(serializedJson);

检查输出的键名、空字符串、列表格式是否和验证通过的JSON一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 10:08:16