【问题标题】:RestSharp Deserialize List<object> returns Could not cast or convert from System.String toRestSharp Deserialize List<object> 返回无法从 System.String 转换或转换为
【发布时间】:2019-02-08 09:01:34
【问题描述】:

我知道有很多关于这个的话题,悬停,我在这里找不到解决方案或找出我做错了什么。

场景:

There are 2 application ( both using Newtonsoft.Json & RestSharp)

Application A serializes a list of objects and returns a string

Application B takes takes the string deserializes back to the list 

在过去的 2 天里,我尝试了多种在互联网上找到的解决方案.. 对我来说没有任何效果..

有人可以告诉我这里缺少什么吗?

谢谢。

如果我应该添加更多详细信息,请告诉我。

用于序列化和反序列化的类:

public class Email
{
    public string Reference { get; set; }
    public string ShortDescription { get; set; }
}

API 创建响应:

//Response
List<Email> apiResponse = new List<Email>();
Task<List<Email>> get = getEmails.GetEmails();
apiResponse = (await get);
return JsonConvert.SerializeObject(apiResponse);

API 响应:

[{"Reference":"01010101","ShortDescription":"Customers Unable To Navigate 
Beyond \"Choose A Level\" Screen on appllicaiton"}, 
{"Reference":"02020202","ShortDescription":"Example2: messenger issue"}]

响应反序列化:

        RestClient client = new RestClient("http://servername:81/");
        client.ClearHandlers();
        RestRequest request = new RestRequest("api/emails/HandleGetRequest", Method.GET);
        request.AddHeader("Accept", "application/json");
        request.AddQueryParameter("query", queryString);

        IRestResponse response = client.Execute(request);
        List<Email> apiResponse;

        if (response.StatusCode == HttpStatusCode.OK)
        {
            // OK 
            apiResponse = JsonConvert.DeserializeObject<List<Email>>(response.Content);
        }
        else
        {
            // NOK
            apiResponse = null;
            Console.Write("ERROR: {0}", response.Content);
            log.FatalFormat("ERROR: {0}", response.Content);

        }

        return apiResponse;

收到错误:

[ArgumentException: Could not cast or convert from System.String to 
System.Collections.Generic.List`1[TestProject.Models.Email].]
Newtonsoft.Json.Utilities.ConvertUtils.EnsureTypeAssignable(Object value, 
Type initialType, Type targetType) +243
Newtonsoft.Json.Utilities.ConvertUtils.ConvertOrCast(Object initialValue, 
CultureInfo culture, Type targetType) +123 Newtonsoft.Json.Serialization.JsonSerializerInternalReader.EnsureType(JsonReader reader, Object value, CultureInfo culture, JsonContract contract, Type targetType) +485


[JsonSerializationException: Error converting value " 
[{"Reference":"01010101","ShortDescription":"Customers Unable To Navigate 
Beyond \"Choose A Level\" Screen on appllicaiton"}, 
{"Reference":"02020202","ShortDescription":"Example2: messenger issue"}]" 
to type 'System.Collections.Generic.List`1[TestProject.Models.Email]'. Path '', 
line 1, position 6633.]

【问题讨论】:

  • 下次你应该分享一个minimal reproducible example
  • 嗨@aloisdg,在以后的任何帖子中都会记住这一点。谢谢。
  • 返回反序列化响应的函数的签名是什么?您收到此错误的哪一行?
  • 嗨 Cid,由于我缺乏知识,我不确定如何回答您的问题,但我会尝试。此处生成错误: apiResponse = JsonConvert.DeserializeObject>(response.Content);我使用了调试器,但在 Newtonsoft 类中失败了
  • 你可以从this fiddle 看到你粘贴的 JSON 格式很好。我怀疑这不是response.Content 中的内容。您所拥有的内容已被引用,因此您要反序列化的是包含整个内容的 JSON 字符串。我对 RestSharp 不熟悉,但我怀疑您是手动序列化为字符串,然后将其传递给框架,然后框架再次通过一些序列化运行该字符串。

标签: c# json c#-4.0 deserialization restsharp


【解决方案1】:

现在要详细说明评论,我想我已经证明了这个理论......

您可以在this fiddle 中看到所描述的 JSON 反序列化工作正常。

这里似乎发生的是 response.Content 是那个 JSON,但是逃脱了。您使用的任何服务器框架都可能再次序列化了结果(string)。

您可以从this fiddle 看到,这会重现相同的错误。

至少换行:

return JsonConvert.SerializeObject(apiResponse);

简单

return apiResponse;

应该导致正确的序列化(框架会这样做,如果您需要进一步配置它而不是查看相关文档)。

不过,我还注意到 the docs 中的 RestSharp 内置了自己的 JSON 反序列化,因此可能也不需要在接收端使用 Newtonsoft.Json。您可以在 recommended usages 中看到各种泛型重载,例如 Execute&lt;T&gt;,它们允许您指定返回类型,框架会反序列化它。

IRestResponse<List<Email>> response = client.Execute<List<Email>>(request);
List<Email> apiResponse = response.Data;

我建议阅读 RestSharp 文档和一些示例。

【讨论】:

  • 嗨@Charles,这确实是正确的。我注意到,如果我创建:string test = "[{\"Reference\":\"-\",\"ShortDescription\":\"No matches found.\"}]" 并再次调用DeserializeObject,它将起作用(因为转义字符已被删除)。 response.content 包含 "[{\"Reference\":\"-\",\"ShortDescription\":\"No matches found.\"}]" 但未删除转义字符,从而产生问题。我已经使用了你的建议并且它正在工作,但我不得不使用JsonConvert.DeserializeObject&lt;List&lt;Email&gt;&gt;(response.Content)',因为response.Data 为空。谢谢您的帮助 !
【解决方案2】:

我认为问题在于反序列化部分中的 IList。

试试:

apiResponse = JsonConvert.DeserializeObject<List<Email>>(response.Content);

【讨论】:

  • "I think""try" 似乎是不确定的答案
  • 对不起那个托尼,我用 List / IList / ienumerable 试过了。并且没有在帖子中更正。我现在修好了
  • 是的,我选择了基于 IList 的受过教育的快速答案。
  • @Cid 为什么不投票而不是发布几乎相同的答案?如果某些条款困扰您,请随时提交对此答案的编辑。
  • @aloisdg 因为我的回答完全不同。请阅读。
猜你喜欢
  • 1970-01-01
  • 2020-08-14
  • 1970-01-01
  • 2017-04-09
  • 1970-01-01
  • 1970-01-01
  • 2012-01-26
  • 2015-10-15
  • 1970-01-01
相关资源
最近更新 更多