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

C#如何生成含嵌套JArray的JSON并发送至远程服务器?

问题:C#序列化时Attributes字段被转为字符串而非数组导致API上传失败

当前请求发送代码

private string SendWebRequest(string url, string requestMethod, string bearer = null, object temp_obj_body = null)
{
    string result = null;
    var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
    httpWebRequest.ContentType = "application/json";
    httpWebRequest.Method = requestMethod.ToUpper();

    // Sets the Security Token
    if (bearer != null)
    {
        httpWebRequest.Headers.Add("Authorization", "Bearer " + bearer);
    }

    //Writes to the request service if body is present
    if (temp_obj_body != null)
    {
        using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream(), Encoding.UTF8))
        {
            JsonSerializerSettings settings = new JsonSerializerSettings();
            settings.CheckAdditionalContent = true;
            settings.Formatting = Formatting.Indented;
            settings.MetadataPropertyHandling = MetadataPropertyHandling.Default;
            settings.NullValueHandling = NullValueHandling.Include;
            settings.PreserveReferencesHandling = PreserveReferencesHandling.All;
            settings.ReferenceLoopHandling = ReferenceLoopHandling.Serialize;
            settings.StringEscapeHandling = StringEscapeHandling.Default;
            settings.TypeNameAssemblyFormatHandling = TypeNameAssemblyFormatHandling.Full;
            settings.TypeNameHandling = TypeNameHandling.All;
            settings.MetadataPropertyHandling = MetadataPropertyHandling.ReadAhead;

            var json = JsonConvert.SerializeObject(temp_obj_body, settings);
            streamWriter.Write(json);
        }
    }

    var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();

    //Reads the response and gets the response.
    using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
    {
        result = streamReader.ReadToEnd();
    }
    return result;
}

当前生成的错误JSON格式

{
    "ID": 1,
    "TypeID": 1,
    "UserName": "tempUser",
    "Attributes": "[{\"ID\":13023,\"Value\":\"Nonemp Status\"},
{\"ID\":13022,\"Value\":\"Research Status\"},
{\"ID\":13021,\"Value\":\"ACT\"},
{\"ID\":13024,\"Value\":\"Temp Status\"},
{\"ID\":13025,\"Value\":\"Temp\"}]
}

期望的正确JSON格式

{
    "ID": 1,
    "TypeID": 1,
    "UserName": "tempUser",
    "Attributes": [{"ID":13023,"Value":"Nonemp Status"},
{"ID":13022,"Value":"Research Status"},
{"ID":13021,"Value":"ACT"},
{"ID":13024,"Value":"Temp Status"},
{"ID":13025,"Value":"Temp"}]
}

解决方案

1. 问题根源

你的temp_obj_body对象中,Attributes字段的类型是字符串(string),而非集合类型(如List<T>或JArray)。序列化时字符串会被转义为带引号的JSON字符串,无法被第三方API解析为数组。

2. 具体修复步骤

  • 定义强类型数据模型
    创建对应的数据类,让Attributes成为集合类型:

    public class RequestBodyModel
    {
        public int ID { get; set; }
        public int TypeID { get; set; }
        public string UserName { get; set; }
        public List<AttributeItem> Attributes { get; set; }
    }
    
    public class AttributeItem
    {
        public int ID { get; set; }
        public string Value { get; set; }
    }
    
  • 简化序列化配置
    移除不必要的序列化设置(如TypeNameHandling.All、PreserveReferencesHandling.All),这些配置会生成第三方API不需要的额外字段:

    var settings = new JsonSerializerSettings
    {
        Formatting = Formatting.Indented,
        NullValueHandling = NullValueHandling.Include,
        ReferenceLoopHandling = ReferenceLoopHandling.Ignore // 避免循环引用问题
    };
    
  • 构造正确的请求对象
    确保传入的temp_obj_body中,Attributes是集合实例而非字符串:

    var requestBody = new RequestBodyModel
    {
        ID = 1,
        TypeID = 1,
        UserName = "tempUser",
        Attributes = new List<AttributeItem>
        {
            new AttributeItem { ID = 13023, Value = "Nonemp Status" },
            new AttributeItem { ID = 13022, Value = "Research Status" },
            // 添加其他属性项
        }
    };
    
    var response = SendWebRequest(apiUrl, "POST", bearerToken, requestBody);
    
  • 若无法修改原始对象类型
    若只能拿到Attributes的字符串形式,先反序列化为集合再替换:

    // 假设temp_obj_body是动态对象或已有类实例
    var attributesStr = temp_obj_body.Attributes.ToString();
    temp_obj_body.Attributes = JsonConvert.DeserializeObject<List<AttributeItem>>(attributesStr);
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 21:16:59