添加课外班

时间:2020-12-23 16:24:45

标签: c# restsharp

我正在使用 RestSharp。我正在尝试创建此 JSON:

            //request.AddParameter("application/json", "{\"properties\":{\"name\":\"{0}\",\"hs_product_id\":\"{1}\",\"hs_recurring_billing_period\":\"24\",\"recurringbillingfrequency\":\"monthly\",\"quantity\":\"1\",\"price\":\"{2}\"}}", ParameterType.RequestBody);

如何为 LineItemHubSpotModel 类创建一个名为 properties 的包装器?这是我的代码:

        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");

        request.AddJsonBody(Serialize(GetLineItemHubSpotModel(name, productId, price)));
        //request.AddParameter("application/json", "{\"properties\":{\"name\":\"{0}\",\"hs_product_id\":\"{1}\",\"hs_recurring_billing_period\":\"24\",\"recurringbillingfrequency\":\"monthly\",\"quantity\":\"1\",\"price\":\"{2}\"}}".Replace("{0}", name).Replace("{1}", productId).Replace("{2}", price), ParameterType.RequestBody);
        IRestResponse response = client.Execute(request);

        RestSharp.Deserializers.JsonDeserializer deserial = new JsonDeserializer();

        return deserial.Deserialize<LineItemHubSpotModel>(response);
    }

    private object Serialize<T>(T item)
    {
        return JsonConvert.SerializeObject(item);
    }

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

        return model;
    }

1 个答案:

答案 0 :(得分:1)

如果您只想包装对象,可以使用具有该属性的类来完成,或者仅使用匿名类型,例如:

var myObject = GetLineItemHubSpotModel(name, productId, price);
var itemToSerialise = new { properties = myObject};
request.AddJsonBody(Serialize(itemToSerialise));
相关问题