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

str*_*ica 5 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);
}
Run Code Online (Sandbox Code Playgroud)

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

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

public class ProductInformation
{
    public string ProductName { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

当我使用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>
Run Code Online (Sandbox Code Playgroud)

产品有2个产品

但是当我尝试使用JSON(Content-Type:application/json)提供相同的东西时,Products列表为空

{
  "ProductAdd": {
    "Products": [
      {
        "ProductInformation": { "ProductName": "Seahorse Necklace" }
      },
      {
        "ProductInformation": { "ProductName": "Ping Pong Necklace" }
      }
    ]
  }
}
Run Code Online (Sandbox Code Playgroud)

产品为空

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

什么会解决这个问题?

谢谢

编辑:您使用哪些序列化程序用于XML和Json?XML:XmlSerializer JSON:Newtonsoft

Bri*_*ers 5

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

  {
    "Products": [
      {
        "ProductInformation": { "ProductName": "Seahorse Necklace" }
      },
      {
        "ProductInformation": { "ProductName": "Ping Pong Necklace" }
      }
    ]
  }
Run Code Online (Sandbox Code Playgroud)

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

public class RootObject
{
    public ProductAdd ProductAdd { get; set; }
}
Run Code Online (Sandbox Code Playgroud)