【问题标题】:Restsharp deserialize failed when sending Dictionary<int,string> parameter to RestAPI将 Dictionary<int,string> 参数发送到 RestAPI 时,Restsharp 反序列化失败
【发布时间】:2015-11-18 08:06:46
【问题描述】:

我已经创建了一个 restsharp api:

object Ping(Dictionary<int, string> item);

此 api 返回常量字符串。 调用它时会出现 BadRequest http 状态,并显示以下消息:

Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'System.Collections.Generic.Dictionary`2[System.Int32,System.String]' 

因为该类型需要一个 JSON 对象(例如 {"name":"value"})才能正确反序列化。 要修复此错误,请将 JSON 更改为 JSON 对象(例如 {"name":"value"})或将反序列化类型更改为数组或实现集合接口的类型(例如 ICollection、IList),例如可以从 JSON 数组反序列化的 List . JsonArrayAttribute 也可以添加到类型中以强制它从 JSON 数组中反序列化。 路径'',第 1 行,位置 1。

RestSharp 似乎不知道如何反序列化字典。我尝试使用 Json.NET 对其进行序列化,通过 JSON 发送到服务器并在服务器端反序列化,它确实有效。

我已经读过,在以前的 RestSharp 版本中可以替换序列化程序类,是否可以在 105.2.3.0 上进行?如何? 您有其他想法可以帮我解决这个问题吗?

【问题讨论】:

  • 你能粘贴你的json吗?

标签: .net rest json.net restsharp json-deserialization


【解决方案1】:

您可以尝试使用以下方法反序列化对字典的响应:

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

var jsonDataDictionary = deserializer.Deserialize<Dictionary<int, string>>(response); 

var valueFromDictionary =  jsonDataDictionary[0]; //to get element value

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-06
    • 1970-01-01
    • 1970-01-01
    • 2011-10-17
    相关资源
    最近更新 更多