【问题标题】:Post JSON object array to a Web API将 JSON 对象数组发布到 Web API
【发布时间】:2017-05-04 02:50:40
【问题描述】:

我很难找到解决此问题的方法。 我的 API 控制器无法获取我发布的数组的内容,并且总是返回 0 元素。

模型类:

public class Author
{
    public int id { get; set; }
    public int referenceId{ get; set; }

    [Newtonsoft.Json.JsonIgnoreAttribute]
    public virtual ICollection<AuthorBook> AuthorBooks { get; set; }
}

public class AuthorBook
{
    public int authorId { get; set; }
    public int bookId { get; set; }
}

API 控制器方法:

[Route("api/authorBooks")]
[HttpPost]
public IList getAuthorBooks(Author author)
{
    return author.AuthorBooks.ToList();
}

JavaScript 客户端:

 var auhtorItem =
      {
          "id": 8,
          "referenceId" : 1 ,
          "AuthorBooks": [{ authorId: 9, bookId : 23 }, { authorId: 9 , bookId  : 25}]
      };

return $.ajax({
    url: booksUrl + "authorBooks",
    type: 'POST',
    data: JSON.stringify(auhtorItem ),
    dataType: 'json',
    contentType: 'application/json',
    crossDomain: true,
    cache: false
});

我能够获取 id 和 referenceId 值,但是 AuthorBooks 是空的,并且计数是 0 而不是 2。

知道为什么吗?

【问题讨论】:

  • 因为Newtonsoft.Json.JsonIgnoreAttribute 存在于AuthorBooks
  • 这不是问题。 Newtonsoft.Json.JsonIgnoreAttribute 不应该出现在 AuthorBooks 上,但是,在您展示给我们的代码中。如果您在此处粘贴的代码与实际程序中的代码不同,edit此处的代码以匹配您的实际问题。
  • this is not the problem. Newtonsoft.Json.JsonIgnoreAttribute should not be present on AuthorBooks - 那为什么它会出现在代码片段中?
  • 嘿@degant你是对的!!!但我别无选择保留 Newtonsoft.Json.JsonIgnoreAttribute 否则当我想显示与作者相关的书籍时,我将有一个循环循环
  • @user708683 不幸的是,您必须将其删除。为了避免循环,您可以根据需要为请求/响应创建包装类

标签: c# json asp.net-web-api


【解决方案1】:

尝试从 AuthorBooks 属性中删除 Newtonsoft.Json.JsonIgnoreAttribute 属性,以便在 JSON 序列化和反序列化期间包含它:

public virtual ICollection<AuthorBook> AuthorBooks { get; set; }

而不是

[Newtonsoft.Json.JsonIgnoreAttribute]
public virtual ICollection<AuthorBook> AuthorBooks { get; set; }

您可以阅读更多关于 JsonIgnoreAttribute 及其示例的信息,了解它是如何工作的。

【讨论】:

  • 嘿@degant你是对的!!!下次我会在确认一些我不确定的东西之前进行测试!但我别无选择保留 Newtonsoft.Json.JsonIgnoreAttribute,否则当我想显示与作者相关的书籍时,我将有一个循环循环。您有关于如何根据需要为请求/响应创建包装类的想法或示例吗?
  • @user708683 你可以试试this or this
  • 谢谢您,先生,祝您有美好的一天:)
猜你喜欢
  • 2015-03-22
  • 1970-01-01
  • 1970-01-01
  • 2012-12-01
  • 1970-01-01
  • 2020-12-03
  • 1970-01-01
  • 2018-01-25
  • 1970-01-01
相关资源
最近更新 更多