gpt4 book ai didi

c# - 无法将 List<> 对象序列化/反序列化为 JSON

转载 作者:太空狗 更新时间:2023-10-30 00:38:52 26 4
gpt4 key购买 nike

我正在开发 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 应用程序 A 中,我返回以下内容:-

[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,我调用操作方法如下:-

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);

但是当我尝试反序列化输出时我会得到以下异常:-

Error converting value "[{"operation":{"result":{"status":"Success","message":"Resource has been added successfully to ......"},"name":"CREATE RESOURCE"}},{"operation":{"result":{"status":"Failed","message":"Account addition "},"name":"ADD ACCOUNTS"}}]" to type 'System.Collections.Generic.List`1[S.ViewModels.CRUDOutput]'. Path '', line 1, position 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\\\"}}]\""

所以有人可以建议为什么我无法反序列化为对象列表吗?

最佳答案

您粘贴的输出被编码为 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

关于c# - 无法将 List<> 对象序列化/反序列化为 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37702598/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com