【问题标题】:RestSharp Post Json ObjectRestSharp Post Json 对象
【发布时间】:2021-05-18 10:34:38
【问题描述】:

我正在尝试使用 RestSharp 发布一个简单的 Json 对象以添加新产品。我收到来自服务器的错误响应 "{"status":400,"error":"您提交的 JSON 中有问题:'{'product':{' 中第 1 行第 2 列 [parse.c:724] 出现意外字符(在 之后) name':'产品名称','opt1':'颜色'}}"}"

我的代码:

////
var json = "{\'product\':{\'name\':\'Product name\',\'opt1\':\'Colour\'}}";

IRestClient restClient = new RestClient();
IRestRequest request = new RestRequest()
{
    Resource = "https://api.targetsite.com/products/"
};

request.AddHeader("Content-Type", "application/json");
request.AddHeader("Accept", "application/xml");
request.AddHeader("authorization", "Bearer " + token);
request.RequestFormat = DataFormat.Json;
request.AddJsonBody(json);

IRestResponse response = restClient.Post(request);
////

我设法使用 curl 语句实现了我想要的结果,但我想使用 RestSharp 来实现。

卷曲语句 -

curl -X POST -H "Content-type: application/json" -H "Authorization: Bearer <ACCESS_TOKEN>"
https://api.targetsite.com/products/ -d '{"product":{"name":"Product name","opt1":"Colour"}}'

这个 HttpClient 调用也可以正常工作

   using (var httpClient = new HttpClient())
{
    using (var request = new HttpRequestMessage(new HttpMethod("POST"), "https://api.targetsite.com/products/"))
    {
        request.Headers.TryAddWithoutValidation("Authorization", "Bearer <ACCESS_TOKEN>"); 

        request.Content = new StringContent("{\"product\":{\"name\":\"Product name\",\"opt1\":\"Colour\"}}");
        request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json"); 

        var response = await httpClient.SendAsync(request);
    }
}

【问题讨论】:

    标签: c# json restsharp


    【解决方案1】:

    您调用的 API 似乎受到限制。

    当您使用 curl 发送 json 时,您使用的是不同的分隔符(" 而不是 ')。

    我的猜测是,当使用 ' 时,您调用的 API 没有正确反序列化 JSON。

    您可以尝试将转义的 ' 替换为 " 或替换代码中的这一行:request.AddJsonBody(json)request.AddJsonBody(Newtonsoft.Json.JsonConvert.DeserializeObject(json)) 前提是您已经安装了 newtonsoft 软件包。

    【讨论】:

    • 感谢您的回复,但这也没有用。现在我得到了这个错误 "{\"type\":\"Bad Request\",\"message\":\"Required parameter missing: product\"}"。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-06
    • 1970-01-01
    相关资源
    最近更新 更多