【发布时间】: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