【发布时间】:2020-04-22 13:08:42
【问题描述】:
我已经用实体框架搭建了一个 web api 控制器。 每当我发布一个 json 对象时,它都会起作用。但是每当 JSON 对象包含在数组 [{},{},] 中时,我都会不断收到错误消息。 下面通过 Postman 报错:
"Message": "The request is invalid.",
"ModelState": {
"incidence": [
"Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'TSCAPP.Models.Incidence' because the type requires a JSON object (e.g. {\"name\":\"value\"}) to deserialize correctly.\r\nTo 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.\r\nPath '', line 1, position 1."
POST 控制器:
[ResponseType(typeof(Incidence))]
public IHttpActionResult PostIncidence(Incidence incidence)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
db.Incidences.Add(incidence);
db.SaveChanges();
return CreatedAtRoute("DefaultApi", new { id = incidence.RegistrationID }, incidence);
}
发病率模型
public class Incidence
{
[Key]
public int RegistrationID { get; set; }
[Required]
public string Name { get; set; }
[Required]
[MinLength(6)]
public string TSCNO { get; set; }
[Required]
[DataType(DataType.EmailAddress)]
public string EmailAddress { get; set; }
public string CellPhone { get; set; }
public string IncidenceType { get; set; }
public string RequestType { get; set; }
public string County { get; set; }
public string ExactLocation { get; set; }
public string Request { get; set; }
public int? RoleID { get; set; }
[DataType(DataType.MultilineText)]
public string FeedBack { get; set; }
}
已发布 JSON 文件
[ { “注册ID”:1, “姓名”:“埃文”, “TSCNO”:“662621”, "电子邮件地址": "evan@mail.com", “手机”:“254722543778”, “发病类型”:空, “请求类型”:空, “县”:“西波科特”, "ExactLocation": "Kapenguria", “请求”:“无”, “角色ID”:2, “回馈”: ”” }, { “注册ID”:2, “姓名”:“约翰”, “TSCNO”:“607921”, "电子邮件地址": "john@mail.com", “手机”:“254700172168”, “发病类型”:空, “请求类型”:空, “县”:“夸莱”, "ExactLocation": "Mkongani", “请求”:“依赖”, “角色ID”:2, “回馈”: ”” } ]
【问题讨论】:
-
向我们展示您发布的
Incidence类和 json
标签: c# json asp.net-mvc