c# - 使用 FromBody 在 WebAPI 中建模的对象的 JSON 数组

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

我正在创建一个 Web Api 方法,它应该通过 XML 或 JSON 接受对象列表并将它们添加到数据库中。

这是我目前拥有的一个非常基本的版本:

[HttpPost]
public HttpResponseMessage Put([FromBody]ProductAdd productAdd)
{
    //do stuff with productadd object
    return Request.CreateResponse(HttpStatusCode.OK);
}

它接受的对象列表的模型结构如下:

public class ProductAdd
{
    public List<ProductInformation> Products { get; set; }
}

public class ProductInformation
{
    public string ProductName { get; set; }
}

当我使用 XML - (Content-Type: application/xml) 时,上面的代码完美运行

<?xml version="1.0" encoding="utf-8"?>
<ProductAdd>
    <Products>  
        <ProductInformation>
            <ProductName>Seahorse Necklace</ProductName>
        </ProductInformation>
    </Products>
    <Products>  
        <ProductInformation>
            <ProductName>Ping Pong Necklace</ProductName>
        </ProductInformation>
    </Products>
</ProductAdd>

Products has 2 Items

但是当我尝试使用 JSON(内容类型:application/json)提供相同的内容时,产品列表是空的

{
  "ProductAdd": {
    "Products": [
      {
        "ProductInformation": { "ProductName": "Seahorse Necklace" }
      },
      {
        "ProductInformation": { "ProductName": "Ping Pong Necklace" }
      }
    ]
  }
}

Products is null

当另一个对象中有一个对象数组时,JSON 序列化程序是否存在问题?

有什么办法可以解决这个问题吗?

谢谢

编辑: 你对 XML 和 Json 使用什么序列化器? XML:XmlSerializer JSON:牛顿软件

最佳答案

您发送到 Web API 方法的 JSON 与您要反序列化的结构不匹配。与 XML 不同,JSON 中的根对象没有名称。您需要从 JSON 中删除包装器对象才能使其正常工作:

  {
    "Products": [
      {
        "ProductInformation": { "ProductName": "Seahorse Necklace" }
      },
      {
        "ProductInformation": { "ProductName": "Ping Pong Necklace" }
      }
    ]
  }

或者,您可以更改您的类结构以添加一个包装类,但您还需要更改您的 XML 以匹配它。

public class RootObject
{
    public ProductAdd ProductAdd { get; set; }
}

关于c# - 使用 FromBody 在 WebAPI 中建模的对象的 JSON 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27066887/

相关文章:

xml - Scala XML\\复制 xmlns 属性。为什么以及如何阻止它?

javascript - 如何将javascript对象转换为字符串?

c# - 如何使用 linq 仅对具有相同属性的后续项目进行分组

c# - 在unity3d中访问android jar

c# - 这个并行异步调用可以简化吗?

xml - 我如何在不结束该部分的情况下在 CDATA 部分中写入文字 "]]>"

java - 在 Java 中复制 XML 文件以写入新的 XML 文件

javascript - 将字符串格式化为 JSON 对象以在 HTML 中显示在带有/[(ngModel)] 的文本区域中

ios - objective-c - 尝试将 "raw" "application/json"数据发布到服务器 API

c# - 从不允许构造函数参数的类型参数 T 实例化有什么用?