ASP.NET Core 6 Web API: Error when posting data from swagger The JSON value could not be converted to Model.ModelName

huangapple go评论55阅读模式
英文:

ASP.NET Core 6 Web API: Error when posting data from swagger The JSON value could not be converted to Model.ModelName

问题

以下是您提供的代码的翻译:

我刚刚遇到了一个问题。我有两个模型 `Department`  `Student`:

    public class Department
    {
        public int Id { get; set; }
        public string DepartmentName { get; set; }
        public int DepartmentCapacity { get; set; }
        public List<Student>? Students { get; set; }
    }

    public class Student
    {
        public int id { get; set; }
        public string StudentName { get; set; }
        public string StudentAge { get; set; }
        public int Department_id { get; set; }
        public Department? Department { get; set; }
    }

 Swagger 中,当我要添加一个 `Department` 时,它要求我插入以下细节:

    {
      "id": 1,
      "departmentName": "IT",
      "departmentCapacity": 20,
      "students": [
        {
          "id": 0,
          "studentName": "string",
          "studentAge": "string",
          "department_id": 0,
          "department": "string"
        }
      ]
    }

我没有传递学生细节,因为它是一个可为空的集合。

当点击 `Execute` 时(控制器的操作方法尚未调用),我得到了以下错误:

    {
      "type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
      "title": "发生了一个或多个验证错误。",
      "status": 400,
      "traceId": "00-aab9a33164e1e58039404c004dfbec6b-317a50661e166115-00",
      "errors": {
        "department": [
          "需要填写部门字段。"
        ],
        "$.students[0].department": [
          "无法将 JSON 值转换为 OneToOneRelationshipWebApi.Model.Department。路径: $.students[0].department | 行号: 10 | 行中的字节位置: 28。"
        ]
      }
    }

在添加一个 `Student` 时,它要求我输入以下细节:

    {
      "id": 0,
      "studentName": "Abhishek",
      "studentAge": "23",
      "department_id": 1,
      "department": {
        "id": 0,
        "departmentName": "string",
        "departmentCapacity": 0,
        "students": [
          "string"
        ]
      }
    }

在执行时,我得到了以下错误:

    "errors": {
        "student": [
          "需要填写学生字段。"
        ],
        "$.department.students[0]": [
          "无法将 JSON 值转换为 OneToOneRelationshipWebApi.Model.Student。路径: $.department.students[0] | 行号: 10 | 行中的字节位置: 14。"
        ]
      }

请您确认我在这里做错了什么,以及如何修复它?

我尝试添加了 NewtonSoft Json 但没有帮助,也尝试了各种可能的方式修复它,但仍然得到相同的错误。
英文:

I just came up with one issue. I have 2 models Department and Student:

public class Department
{
public int Id { get; set; }
public string DepartmentName { get; set; }
public int DepartmentCapacity { get; set; }
public List<Student>? Students { get; set; }
}
public class Student
{
public int id { get; set; }
public string StudentName { get; set; }
public string StudentAge { get; set; }
public int Department_id { get; set; }
public Department? Department { get; set; }
}

In Swagger, when I'm going to add a Department, it asks me to insert these details:

{
"id": 1,
"departmentName": "IT",
"departmentCapacity": 20,
"students": [
{
"id": 0,
"studentName": "string",
"studentAge": "string",
"department_id": 0,
"department": "string"
}
]
}

I'm not passing the student details as it's a nullable collection.

When clicking on Execute (the controller's action method is not called yet) I get this error:

{
"type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
"title": "One or more validation errors occurred.",
"status": 400,
"traceId": "00-aab9a33164e1e58039404c004dfbec6b-317a50661e166115-00",
"errors": {
"department": [
"The department field is required."
],
"$.students[0].department": [
"The JSON value could not be converted to OneToOneRelationshipWebApi.Model.Department. Path: $.students[0].department | LineNumber: 10 | BytePositionInLine: 28."
]
}
}

And while adding a Student, it asks me to enter these details:

{
"id": 0,
"studentName": "Abhishek",
"studentAge": "23",
"department_id": 1,
"department": {
"id": 0,
"departmentName": "string",
"departmentCapacity": 0,
"students": [
"string"
]
}
}

When executing, I get this error:

"errors": {
"student": [
"The student field is required."
],
"$.department.students[0]": [
"The JSON value could not be converted to OneToOneRelationshipWebApi.Model.Student. Path: $.department.students[0] | LineNumber: 10 | BytePositionInLine: 14."
]
}

Please, can you confirm what I'm doing wrong here and how I can fix it?

I tried to add the NewtonSoft Json but it didn't help, also tried to fix it in all possible ways but still getting the same error.

答案1

得分: 1

在第一种情况(当您想要添加部门时),会发生错误,因为您将“department”属性的值传递为“string”。如果您不想传递“department”对象,只需从JSON中删除该属性:

{
  "id": 1,
  "departmentName": "IT",
  "departmentCapacity": 20,
  "students": [
    {
      "id": 0,
      "studentName": "string",
      "studentAge": "string",
      "department_id": 0//, remove this comma
      //"department": "string" //remove this line
    }
  ]
}

如果您想要填充“department”属性,您必须像这样做:

{
  "id": 1,
  "departmentName": "IT",
  "departmentCapacity": 20,
  "students": [
    {
      "id": 0,
      "studentName": "string",
      "studentAge": "string",
      "department_id": 0,
      "department": {
          "id": 0,
          "departmentName": "string",
          "departmentCapacity": 0
      }
    }
  ]
}

再次在第二种情况下,当您尝试添加学生时,删除以下部分:

{
  "id": 0,
  "studentName": "Abhishek",
  "studentAge": "23",
  "department_id": 1,
  "department": {
    "id": 0,
    "departmentName": "string",
    "departmentCapacity": 0//, -> remove this comma
    // "students":[ -> remove this part
    //  "string"   -> remove this part
    // ] -> remove this part
  }
}

如果您想要填充“students”属性,您必须像这样做:

{
  "id": 0,
  "studentName": "Abhishek",
  "studentAge": "23",
  "department_id": 1,
  "department": {
    "id": 0,
    "departmentName": "string",
    "departmentCapacity": 0,
    "students":[ 
      {
         "id": 0,
         "studentName": "Abhishek",
         "studentAge": "23",
         "department_id": 1
      },
      {
         "id": 1,
         "studentName": "Abhishek",
         "studentAge": "23",
         "department_id": 2
      } 
     ] 
  }
}

总之,如果您想要使属性为“null”,您必须将其从JSON中删除,或者用所有参数填充它,这些参数将具有一些默认空值。

英文:

The error in case one (when you want to add Department) is thrown, because you are passing as value of "department" property "string". If you don't want to pass "department" object, just remove property from json:

{
"id": 1,
"departmentName": "IT",
"departmentCapacity": 20,
"students": [
{
"id": 0,
"studentName": "string",
"studentAge": "string",
"department_id": 0//, remove this comma
//"department": "string" //remove this line
}
]
}

I you want to have "department" property fulfilled, you have to do it like this:

{
"id": 1,
"departmentName": "IT",
"departmentCapacity": 20,
"students": [
{
"id": 0,
"studentName": "string",
"studentAge": "string",
"department_id": 0,
"department": {
"id": 0,
"departmentName": "string",
"departmentCapacity": 0
}
}
]
}

Again in case 2, when you are trying to add Student, remove

{
"id": 0,
"studentName": "Abhishek",
"studentAge": "23",
"department_id": 1,
"department": {
"id": 0,
"departmentName": "string",
"departmentCapacity": 0//, -> remove this comma
//"students":[ -> remove this part
// "string"   -> remove this part
// ] -> remove this part
}
}

I you want to have "students" property fulfilled, you have to do it like this:

{
"id": 0,
"studentName": "Abhishek",
"studentAge": "23",
"department_id": 1,
"department": {
"id": 0,
"departmentName": "string",
"departmentCapacity": 0,
"students":[ 
{
"id": 0,
"studentName": "Abhishek",
"studentAge": "23",
"department_id": 1
},
{
"id": 1,
"studentName": "Abhishek",
"studentAge": "23",
"department_id": 2
} 
] 
}
}

Conclusion is, if you want to have that property "null", you have to remove it from json, or fulfill it with all parameters, which will have some default empty values.

答案2

得分: 1

我不确定你如何在你的项目中配置 NewtonSoft,但它在我的项目中有效。

首先,在 Program.cs 中配置 NewtonSoft 如下:

builder.Services.AddControllers().AddNewtonsoftJson(options =>
{
    options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
    options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
});

如果你想发送不包含 Student 部分的 Department 请求,你可以像这样发送请求:

{
  "id": 1,
  "departmentName": "TT",
  "departmentCapacity": 15
}

然后 Swagger 将发送这个 JSON 数据而不会出现 400 错误。

如果你想发送 Student 请求,你只需要在你的 JSON 中删除 department_iddepartment

{
  "id": 1,
  "studentName": "AA",
  "studentAge": "23"
}
英文:

I am not sure how you configure NewtonSoft in your project, But it works in my project.

First configure NewtonSoft like this in Program.cs

builder.Services.AddControllers().AddNewtonsoftJson(options =>
{
options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
});

If you want to send Department request without Student part, You can just send your request like this:

{
"id": 1,
"departmentName": "TT",
"departmentCapacity": 15,
}

Then swagger will send this json data without 400 error

ASP.NET Core 6 Web API: Error when posting data from swagger The JSON value could not be converted to Model.ModelName

If you want to send Student request, you also just need to delete department_id and department in your json:

{
"id": 1,
"studentName": "AA",
"studentAge": "23",  
}

huangapple
  • 本文由 发表于 2023年6月1日 04:35:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/76377093.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定