【问题标题】:.net core API sending array object.net core API 发送数组对象
【发布时间】:2019-03-06 11:22:53
【问题描述】:

我有一个学生类,其中包含数组 StudentPhones。当我从 Student 类中删除 StudentPhones 属性时,与 Postman 一起发布时效果很好。但是当添加 StudentPhones 属性时,邮递员会给我这个错误:

{ “学生电话”:[ “无法将当前 JSON 数组(例如 [1,2,3])反序列化为类型 'DataAccess.StudentPhone',因为该类型需要 JSON 对象(例如 {\"name\":\"value\"})才能正确反序列化.\r\n要修复此错误,请将 JSON 更改为 JSON 对象(例如 {\"name\":\"value\"})或将反序列化类型更改为数组或实现集合接口的类型(例如ICollection, IList) 之类的 List 可以从 JSON 数组反序列化。还可以将 JsonArrayAttribute 添加到该类型以强制它从 JSON 数组反序列化。\r\nPath 'StudentPhones',第 4 行,第 23 位。" ] }

    public class Student
    {
        public string StudentName { get; set; }
        public string StudentSurname { get; set; }
        public StudentPhone StudentPhones { get; set; }
    }

    public class StudentPhone
    {
        public int PhoneType{ get; set; }
        public string PhoneNumber { get; set; }
    }

    public async Task<ServiceResult> SaveStudent([FromBody]Student student)
    {
    }

我怎样才能发布这个 json? (我实际使用的是angular 6,邮递员只是举例)

我的 json

{
  "studentName": "test",
  "studentSurname": "test",
  "studentPhones": [
    {
      "phoneType": 1,
      "phoneNumber ": "111111111"
    },
    {
      "phoneType": 2,
      "phoneNumber ": "2222222222"
    }
  ],
}

【问题讨论】:

  • 为什么不在Student 类中将StudentPhones 声明为StudentPhone 的数组或列表?
  • 我太粗心了 :) 。感谢您的回复。我为这个问题感到很惭愧
  • 没关系!如果你真的想,你可以删除帖子。它可能会在某个时候被关闭和删除,因为这是代码中的一个简单错误。
  • 我尝试删除问题,但 stackoverflow 拒绝。

标签: c# angular asp.net-core postman asp.net-core-webapi


【解决方案1】:

您的 JSON 中有一系列电话,因此您的模型中应该有 public StudentPhone StudentPhones { get; set; },而不是 public List&lt;StudentPhone&gt; StudentPhones { get; set; }

【讨论】:

  • 你应该使用StudentPhones列表public List&lt;StudentPhone&gt; StudentPhones { get; set; }
  • 我太粗心了 :) 。感谢您的回复。我为这个问题感到很惭愧
  • @HasanOzdemir 有时会发生在我们所有人身上。我会否决你的问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-05-17
  • 1970-01-01
  • 2021-08-31
  • 2017-05-15
  • 2021-02-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多