【发布时间】:2021-08-10 03:04:48
【问题描述】:
我有这个代码,我试图从 ac# web api 中检索 json 数据,当我尝试反序列化我得到的 json 时:无法反序列化当前 JSON 对象(例如 {"name ":"value"}) 转换为 'ModularWebApp.Models.LutUsers[]' 类型,因为该类型需要 JSON 数组(例如 [1,2,3])才能正确反序列化。 要修复此错误,请将 JSON 更改为 JSON 数组(例如 [1,2,3])或更改反序列化类型,使其成为普通的 .NET 类型(例如,不是像整数这样的原始类型,而不是像这样的集合类型可以从 JSON 对象反序列化的数组或列表。 JsonObjectAttribute 也可以添加到类型中以强制它从 JSON 对象反序列化。 路径“内容”,第 1 行,位置 11。'
我尝试了很多其他方法,但仍然无法正常工作,有什么帮助吗?
这是我的模型
[JsonProperty("matricule_agent")]
public string matricule_agent {get; set;}
[JsonProperty("grade_agent")]
public string grade_agent { get; set; }
[JsonProperty("nom_utils")]
public string nom_utils { get; set; }
[JsonProperty("prenom_utils")]
public string prenom_utils { get; set; }
这是我的控制器
public ActionResult LutUser()
{
ViewBag.Message = "Your LookUp Table Page.";
List<LutUsers> lutUsers = new List<LutUsers>();
LutUsers[] Users = new LutUsers[0];
HttpResponseMessage response = client.GetAsync(client.BaseAddress +
"/user/findusers").Result;
//Checking the response is successful or not which is sent using HttpClient
if (response.IsSuccessStatusCode)
{
//Storing the response details recieved from web api
Response.Write("<script>alert('Connection Made successfully!');</script>");
JavaScriptSerializer js = new JavaScriptSerializer();
// Person[] persons = js.Deserialize<Person[]>(json);
string data = response.Content.ReadAsStringAsync().Result;
lutUsers = JsonConvert.DeserializeObject<List<LutUsers>>(data);
// lutUsers = JsonConvert.DeserializeObject<List<LutUsers>>(data);
Response.Write(Users);
} else
{
Response.Write("<script>alert('Connection not made!');</script>");
}
//returning the employee list to view
return View(lutUsers);
}
【问题讨论】:
-
就像粗体文本所说,如果你想反序列化成一个数组,JSON 期望文本也包含一个像
[ {"name":"value"} ]这样的数组。请注意,JSON 中的[]表示一个任意数组。 -
我是这样弄的,也没用
-
那么你的 json
data是什么样的? -
{"content": [{"id_utilisateurs":1, "matricule_agent":"BE4", "nom_utils":"laguerre", "prenom_utils":"Vellie","sexe_utils":" F”、“dat2naiss_utils”:“15-12-2020”、“grade_agent”:“代理 4”、“email_utils”:“Laguerre.vellie@gmail.com”、“mot2pass_utils”:null、“typ_compte”:“代理", "is_active_utils":1, "date_enreg_utils":"05-05-2021 15:55:00", "affectation":"villate","is_first_login":1, "mot2pass_utils_defaut":null }], "status" :"成功"}
标签: c# arrays asp.net json api