You need to enable JavaScript to run this app. RestSharp下如何为LineItemHubSpotModel创建properties JSON包装层
优惠活动
大模型
产品
解决方案
定价
更多

RestSharp下如何为LineItemHubSpotModel创建properties JSON包装层

解决方案

你遇到的问题核心是强类型序列化的结构和HubSpot接口要求的JSON层级不匹配,同时现有代码存在序列化逻辑bug,按以下步骤调整即可:

1. 新增请求包装类实现properties外层结构

不需要改动原有LineItemHubSpotModel的核心字段逻辑,新增一个外层包装类,将行项目属性作为其Properties属性,序列化时就会自动生成要求的properties节点:

public class LineItemCreateRequest
{
    [JsonProperty("properties")]
    public LineItemHubSpotModel Properties { get; set; }
}

2. 修正原有模型的字段映射,匹配接口字段要求

HubSpot接口要求的字段为小写/下划线命名规则,需要通过JsonProperty特性将模型属性和接口字段做一一映射,同时补上硬编码的固定值字段:

public class LineItemHubSpotModel
{
    [JsonProperty("name")]
    public string Name { get; set; }

    [JsonProperty("hs_product_id")]
    public long HsProductId { get; set; }

    [JsonProperty("hs_recurring_billing_period")]
    public string HsRecurringBillingPeriod { get; set; } = "24";

    [JsonProperty("recurringbillingfrequency")]
    public string RecurringBillingFrequency { get; set; } = "monthly";

    [JsonProperty("quantity")]
    public int Quantity { get; set; }

    [JsonProperty("price")]
    public decimal Price { get; set; }
}

3. 修正现有接口调用的逻辑错误

原代码存在两个影响调用的关键问题:

  • 手动调用JsonConvert.SerializeObject序列化后传给request.AddJsonBody会触发双重序列化,最终请求体会变成带转义的字符串,不符合标准JSON格式要求
  • 构造请求体时没有套上面定义的LineItemCreateRequest包装类,导致JSON层级不匹配

修正后的完整调用代码:

private LineItemHubSpotModel AddLineItems(string name, long productId, decimal price)
{
    var client = new RestClient("https://api.hubapi.com/crm/v3/objects/line_items?hapikey=" + apiKey);
    var request = new RestRequest(Method.POST);
    request.AddHeader("accept", "application/json");
    request.AddHeader("content-type", "application/json");

    // 构造带properties外层结构的请求体
    var requestBody = new LineItemCreateRequest
    {
        Properties = GetLineItemHubSpotModel(name, productId, price)
    };

    // 直接传对象,由RestSharp自动完成JSON序列化,不要手动转字符串
    request.AddJsonBody(requestBody);

    IRestResponse response = client.Execute(request);
    RestSharp.Deserializers.JsonDeserializer deserial = new JsonDeserializer();
    return deserial.Deserialize<LineItemHubSpotModel>(response);
}

private LineItemHubSpotModel GetLineItemHubSpotModel(string name, long productId, decimal price)
{
    return new LineItemHubSpotModel()
    {
        Name = name,
        HsProductId = productId,
        Price = price,
        Quantity = 1,
    };
}

调整完成后,可以直接删除原代码中多余的Serialize<T>泛型方法,避免后续误用引发序列化错误。最终生成的请求体结构和手动拼接的格式完全一致,不需要再做字符串替换操作。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.12 07:54:05