RestSharp将空字符串反序列化为字典错误 [英] RestSharp Deserialization of empty string to Dictionary Error
问题描述
我对RestSharp有点陌生,所以请原谅我的无知。我收到以下错误:
I'm a bit new to RestSharp so please excuse my ignorance. I'm getting the following error:
{"Unable to cast object of type 'System.String' to type 'System.Collections.Generic.IDictionary`2[System.String,System.Object]'."}
此当RestSharp尝试反序列化并将空字符串转换为Dictionary对象时发生。
This happens when RestSharp tries to deserialize and empty string to a Dictionary object.
这是我缩写的Result对象:
Here is the my abbreviated Result object:
public class Result
{
public Dictionary<string, string> assignment_group { get; set; }
}
如果填充了assignment_group,则返回以下内容:
Here is what is returned if assignment_group is populated:
"assignment_group":{"link":"https://someurl/api/now/table/sys_user_group/2c1cf1176f29f5007a3db03f5d3ee4aa","value":"2c1cf1176f29f5007a3db03f5d3ee4aa"}
如果未填充assignment_group,则返回以下内容:
Here is what is returned if assignment_group is not populated:
"assignment_group":""
正在发生的事情是,assignment_group的JSON响应将是字典或空字符串。如果是空字符串,我只会收到错误消息。如何在Result类的Assignment_group属性中容纳两种返回类型?
What is happening is the JSON response for assignment_group will be a Dictionary or an empty string. I will only get the error if it's an empty string. How can I accommodate both return types in my Result class assignment_group property?
在此先感谢您的帮助。
更新:
这是对我有用的解决方案。
Update: Here is working solution for me.
我使用的是Newtonsoft,而不是RestSharp使用的默认反序列化器。杰森代替。这是来自我的包装器类的代码示例:
Instead of default Deserializer used by RestSharp, I used Newtonsoft.Json instead. Here is code example from my wrapper class:
public T Execute<T>(RestRequest request) where T : new()
{
if (request.Method == Method.POST)
client.FollowRedirects = false;
var response = client.Execute<T>(request);
// **** Added Newtonsoft.Json ****
var x = JsonConvert.DeserializeObject<T>(response.Content);
LogRequest(request, client);
LogResponse<T>(response);
ErrorHandling<T>(response);
// ****This is no longer needed. Data is null now****
// return response.Data;
// **** Added ****
return x;
}
推荐答案
您是否正在使用为此自定义序列化器/反序列化器?因为我的理解是涵盖了以下情况(但您的示例未涉及):
Are you making use of a custom serializer/deserializer for this? Because my understanding is that the following cases are covered (but your example is not):
- assignment_group = null;
结果为 assignment_group:空 - assignment_group = new Dictionary();
结果为 assignment_group: {} - assignment_group = new Dictionary(); assignment_group.Add( key, value);
结果为 assignment_group: {键:值}
这也可能与以下内容有关: https://github.com/restsharp/RestSharp/issues/486
This may also be related to: https://github.com/restsharp/RestSharp/issues/486
这篇关于RestSharp将空字符串反序列化为字典错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!