我得到了这个简单的代码,它将从url中消耗api数组。
public ActionResult ViewRecord()
{
ViewBag.Title = "- Geotagging Sub Project Record.";
var webClient = new WebClient();
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls
| SecurityProtocolType.Tls11
| SecurityProtocolType.Tls12;
webClient.Headers.Add(HttpRequestHeader.Cookie, "cookievalue");
string objJson = webClient.DownloadString(@"https://test.com/api/lib_region");
//here we will map the Json to C# class
Models.SubProjectViewRecord oop = JsonConvert.DeserializeObject<Models.SubProjectViewRecord>(objJson);
return View(oop);
}我的模型
namespace portal.Models
{
public class SubProjectViewRecord
{
public string Name { get; set; }
public int Id { get; set; }
}
}以上代码的错误是:
'Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'portal.Models.SubProjectViewRecord' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.
To fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List<T> that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.
Path '', line 1, position 1.'然后,这些是我应用于模型的修正,因为有些回复正在发布。
public class SubProjectViewRecord
{
public List<string> Name { get; set; }
public List<int> Id { get; set; }
}到这一行:
Models.SubProjectViewRecord oop = JsonConvert.DeserializeObject<List<Models.SubProjectViewRecord>>(objJson);但是,错误引起了:
Cannot implicitly convert type 'System.Collections.Generic.List<portal.Models.SubProjectViewRecord>' to 'portal.Models.SubProjectViewRecord'提前谢谢。
发布于 2022-03-14 11:47:30
显然,从错误中可以看出数组中有多个项,这就是为什么会有从api reponse返回的数组。您可以对其使用List<T>,其代码如下所示:
List<Models.SubProjectViewRecord> oop = JsonConvert.DeserializeObject<List<Models.SubProjectViewRecord>>(objJson);假设json数组元素为json对象,其中包含Id和Name成员,则模型如下:
public class SubProjectViewRecord
{
public string Name { get; set; }
public int Id { get; set; }
} 发布于 2022-03-14 11:53:44
首先,您需要知道JSON是如何返回数据的。所以,如果你有这样的东西:
[
{
"name": "",
"id": ""
}
]您需要的是实现这样一个结构的类的列表(比如SubProjectViewRecord)。所以,你会得到这样的东西:
List<SubProjectViewRecord> oop = JsonConvert.DeserializeObject<List<SubProjectViewRecord>>(objJson);如果你看到了,你的错误就是这么说的。它说:“我不能为一个SubProjectViewRecord变量分配一个列表”。
所以,只要确定:
类与JSON结构完全匹配。您为反序列化提供的类(传递给deserialization.的泛型)与接收deserialization.的变量相同。
https://stackoverflow.com/questions/71467196
复制相似问题