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

C#调用API提交数据返回Malformed JSON string错误如何修复

问题根因

报错由两个问题共同导致:

  • JSON拼接语法非法:你手动拼接params参数时存在符号错误,拼接后的字符串为{"information":{序列化的custom对象}"},在custom对象闭合后多了一个无意义的双引号,本身就不符合JSON语法规范,服务端无法正常解析。
  • 数据结构不匹配:接口要求的custom_fields_values字段是数组类型(原始参考payload中该值用[]包裹),但你定义的模型中该字段是单个CustomFieldsValues对象,序列化后输出的是对象结构,和接口要求的数组结构不符。
修复步骤
  1. 调整数据模型定义,将custom_fields_values字段改为集合类型,匹配接口要求的数组结构:
public class CustomField
{
    [JsonProperty(PropertyName = "i_customer")]
    public int? CustomerId { get; set; }

    [JsonProperty(PropertyName = "custom_fields_values")]
    // 修改为List数组类型
    public List<CustomFieldsValues> CustomFieldsValues { get; set; }
}

public class UpdateCustomerCustomFieldsValuesResponse
{
    [JsonProperty(PropertyName = "i_customer")]
    public int? CustomerId { get; set; }
}

public class CustomFieldsValues
{
    [JsonProperty(PropertyName = "i_custom_field")]
    public int CustomFieldId { get; set; }

    [JsonProperty(PropertyName = "db_value")]
    public string DbValue { get; set; }
}
  1. 构造请求对象时,给CustomFieldsValues赋值为集合,不要传入单个对象:
CustomField custom = new CustomField()
{
    CustomerId = customerId,
    CustomFieldsValues = new List<CustomFieldsValues>()
    {
        new CustomFieldsValues()
        {
            CustomFieldId = _portaClient._CustomFieldId,
            DbValue = customFieldId
        }
    }
};
  1. 禁止手动拼接JSON字符串,统一用序列化工具生成完整参数,从根源避免转义、符号错漏问题:
string url = endpoint;
var client = new RestClient(url)
{
    Timeout = -1
};

var request = new RestRequest(Method.POST);
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
// 构造完整参数对象后统一序列化,不要手动拼字符串
var requestParams = new {
    information = custom
};
request.AddParameter("params", JsonConvert.SerializeObject(requestParams));

var response = client.Execute(request);

修复后生成的payload会和参考格式完全一致:{"information":{"i_customer":1,"custom_fields_values":[{"i_custom_field":1,"db_value":"2"}]}},符合接口解析要求。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.03 05:57:31