【问题标题】:How to consume api that return json data as string using RestSharp RestClient in dot NET如何使用 dot NET 中的 RestSharp RestClient 使用将 json 数据作为字符串返回的 api
【发布时间】:2022-02-15 15:10:18
【问题描述】:

我正在使用一个将 json 数据作为字符串返回的 API。那就是它的返回类型是Task<string>。通常 API 返回一个 Response 类的对象,然后由 dot NET 序列化。但在这种情况下,API 返回 Response 类的序列化版本。

我正在尝试使用 RestSharp->RestClient 使用此 API。在 RestClient 方法 ExecutePostAsync(request) 中,该方法将响应反序列化为代替 T 指定的类的对象。我有一个名为 Response 的类,我希望在其中反序列化响应。所以,我提出的要求是,

_restClient.ExecutePostAsync<Response>(request)

现在我面临的问题是 API 响应返回的 json 字符串格式为 "{<json-fields>}",但当接收到 RestClient 时,格式为 \"{<json-fields>}\"。那就是添加转义字符。因此,RestClient 用于序列化和反序列化的 NewtonSoftJSON 会出现错误,Error converting \"{<json-fields>}\" to Response class

当我对 RestResponse 执行验证时,我还需要来自 RestClient 的原始 RestResponse。因此,不能这样做,将响应作为字符串获取并反序列化。那就是我不想这样做,

var restResponse = _restClient.ExecutePostAsync<string>(request);
var data = Deserialize(restResponse.Data);

因为这只会给我 Response 类的对象,但我需要 RestResponse 类的对象来执行验证。

在这种情况下我该怎么办?

【问题讨论】:

  • 你试过这个 SO answer?
  • 这里的问题是ExecutePostAsync本身反序列化了RestResponse的Content字段中的数据并填充到RestResponse的Data字段中,而Content字段中的字符串是转义字符串,所以无法反序列化。我希望这个操作能正常工作。由于我在问题中提到的原因,我不想手动反序列化响应中的数据。

标签: c# .net-core json.net restsharp


【解决方案1】:

通过网上的一些研究,我找到了以下解决方案,

我们将 RestClient 和 RestRequest 初始化为,

RestClient restClient = new RestClient();
RestRequest request = new RestRequest(<url>);

现在由于来自 api 的响应是来自简单字符串的 json 数据,我们可以如下指示请求接受文本响应,

restRequest.AddHeader("Accept", "text/plain");

现在,默认情况下,RestClient 不对响应类型 text/plain 使用 NewtonSoftJson 反序列化。所以,我们需要添加一个处理程序来告诉 RestClient 使用 NewtonSoftJson 反序列化,如下所示,

restClient.AddHandler("text/plain", () => new RestSharp.Serializers.NewtonsoftJson.JsonNetSerializer());

现在我们可以如下提出请求,它会正常工作,

restRequest.AddJsonBody(<body>);
restClient.ExceutePostAsync<T>(restRequest);

我们可以将T 替换为我们希望在其中反序列化响应的类。

参考资料:

https://github.com/restsharp/RestSharp/issues/276

Deserialize JSON with RestSharp

【讨论】:

    【解决方案2】:

    如果您无法修复 api 以响应 json 格式,我看到的唯一方法是清理您的字符串响应:

    var data = Deserialize(restResponse.Data.ToString.Replace('\"',(char)0));
    

    您还应该查看 RestSharp 的文档,您可以通过 [Type] 发出请求以自动反序列化响应:

    var request = new CreateOrder("123", "foo", 10100);
    // Will post the request object as JSON to "orders" and returns a 
    // JSON response deserialized to OrderCreated  
    var result = client.PostJsonAsync<CreateOrder, **OrderCreated**>("orders", request, cancellationToken);
    

    我希望这会有所帮助! ?

    【讨论】:

    • 感谢您的回答。RestSharp 的 ExecutePostAsync 方法也会自动反序列化响应,但由于来自 API 的响应包含转义字符,因此会出错。正如我在问题中提到的那样,我不想反序列化响应中的数据,因为我希望整个响应保持完整以进行验证。所以希望这个自动反序列化能够正常工作。
    猜你喜欢
    • 1970-01-01
    • 2019-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-14
    • 1970-01-01
    • 2018-02-11
    相关资源
    最近更新 更多