c# - 用对象数组修补对象

标签 c# json asp.net-core .net-core json-patch

我在一所学校的类(class)和学生之间建立了多对多关系。这是我的类(class)内容:

public class Course
{
    public Guid CourseId { get; set; }
    public string Name { get; set; }

    public ICollection<CourseStudent> Students { get; set; }
}

public class CourseStudent
{
    public Guid CourseId { get; set; }        
    public Guid StudentId { get; set; }
}

我正在使用 JsonPatch 来修补我的对象。我正在尝试添加到 Students 的集合中,只是添加到集合的末尾:

[
  {
    "op": "add",
    "path": "/Students/-",
    "value": [
       { 
         "CourseId": "07264DC9-9FEB-42E2-B1EF-08D58F58C873", 
         "StudentId": "FB6E6988-4A56-4CA4-86E2-E23090FAD98F"
       }
     ]
  }
]

但是当我提交这个时,我得到一个异常(exception):

"ClassName": "Microsoft.AspNetCore.JsonPatch.Exceptions.JsonPatchException",

"Message": "The value '[\r\n {\r\n \"CourseId\": \"07264DC9-9FEB-42E2-B1EF-08D58F58C873\",\r\n \"StudentId\": \"FB6E6988-4A56-4CA4-86E2-E23090FAD98F\"\r\n }\r\n]' is invalid for target location.",

根据 Json 补丁文档,该结构对我来说看起来是正确的。知道为什么它不接受我的格式吗?

最佳答案

搞清楚了,格式应该是:

[
  {
    "op": "add",
    "path": "/Students/-",
    "value":
       { 
         "CourseId": "07264DC9-9FEB-42E2-B1EF-08D58F58C873", 
         "StudentId": "FB6E6988-4A56-4CA4-86E2-E23090FAD98F"
       }
  }
]

关于c# - 用对象数组修补对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49416381/

相关文章:

c# - 将 Kestrel 暴露于外界的风险

c# - DateTime.ParseExact 上的 CultureInfo?

c# - 使用 C# 作为后台代码在 Xamarin Forms 的框架内创建 StackLayout

c# - 工厂模式和对象持久性

c# - 如何将位图返回给浏览器 WebApi

javascript - 转换用 data() 保存的字符串形式对象

java - 在没有对象映射器的情况下将对象转换为 Jackson 中的 JSON 文件

javascript - 如何修复 `Uncaught SyntaxError: Unexpected token % in JSON at position 3` 以将数据从 Vue 传递到 Iframe?

c# - 不断收到错误 : Cannot access a closed Stream on Asp.net Core 中间件

c# - 使用 .net core 和 mongodb 了解性能