我正在开发2个Web应用程序; A& B.现在我在两个Web应用程序中都有一个名为CRUDOutput的共享类: -
public class CRUDOutput
{
public Operation4 operation { get; set; }
}
public class Operation4
{
public Result result { get; set; }
public string name { get; set; }
}
public class Result
{
public string status { get; set; }
public string message { get; set; }
}
现在在Web应用程序中我正在返回以下内容: -
[HttpPost]
public ActionResult CreateResource(CreateResource cr)
{
List<CRUDOutput> co = new List<CRUDOutput>();
co.Add(JsonConvert.DeserializeObject<CRUDOutput>(crudoutput));
co.Add(JsonConvert.DeserializeObject<CRUDOutput>(crudoutput2));
return Json(JsonConvert.SerializeObject(co));
}
现在来自Web应用程序B,我正在调用action方法如下: -
try
{
using (WebClient wc = new WebClient())
{
string url = "https://localhost:44302/" + "Home/CreateResource";
Uri uri = new Uri(url);
wc.Headers.Add(HttpRequestHeader.ContentType, "application/json");
output = wc.UploadString(uri, data);
}
}
catch (WebException e)
{
}
List<CRUDOutput> result = JsonConvert.DeserializeObject<List< CRUDOutput>>(output);
但是当我尝试反序列化输出时,我会得到以下异常: -
转换值时出错 &#34; [{&#34;操作&#34; {&#34;导致&#34; {&#34;状态&#34;:&#34;成功&#34;&#34;消息&# 34;:&#34;资源有 已成功添加到......&#34;},&#34; name&#34;:&#34; CREATE RESOURCE&#34;}},{&#34;操作&#34; {&#34;导致&#34; {&#34;状态&#34;:&#34;失败&#34;&#34;消息&#34;:&#34;帐户 添加&#34;},&#34;名称&#34;:&#34;添加帐户&#34;}}]&#34;输入 &#39; System.Collections.Generic.List`1 [S.ViewModels.CRUDOutput]&#39 ;.路径&#39;&#39;, 第1行,第464位。
现在,从Web应用程序A返回的JSON将如下: -
"\"[{\\\"operation\\\":{\\\"result\\\":{\\\"status\\\":\\\"Success\\\",\\\"message\\\":\\\"Resource 123 rfrf has been added successfully \\\"},\\\"name\\\":\\\"CREATE RESOURCE\\\"}},{\\\"operation\\\":{\\\"result\\\":{\\\"status\\\":\\\"Failed\\\",\\\"message\\\":\\\"Account addition \\\"},\\\"name\\\":\\\"ADD ACCOUNTS\\\"}}]\""
所以有人可以建议为什么我无法反序列化为对象列表吗?
答案 0 :(得分:7)
您粘贴的输出被编码为JSON两次。比较两者之间的区别:
"\"[{\\\"operation\\\":{\\\"result\\\":{\\\"status\\\":\\\"Success\\\",\\\"message\\\":\\\"Resource 123 rfrf has been added successfully \\\"},\\\"name\\\":\\\"CREATE RESOURCE\\\"}},{\\\"operation\\\":{\\\"result\\\":{\\\"status\\\":\\\"Failed\\\",\\\"message\\\":\\\"Account addition \\\"},\\\"name\\\":\\\"ADD ACCOUNTS\\\"}}]\""
和
"[{\"operation\":{\"result\":{\"status\":\"Success\",\"message\":\"Resource 123 rfrf has been added successfully \"},\"name\":\"CREATE RESOURCE\"}},{\"operation\":{\"result\":{\"status\":\"Failed\",\"message\":\"Account addition \"},\"name\":\"ADD ACCOUNTS\"}}]"
这是因为您将结果编码为Json两次。替换:
return Json(JsonConvert.SerializeObject(result));
与
return Json(result); // This encodes as JSON automatically