我正在创建一个 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>
但是当我尝试使用 JSON(内容类型:application/json)提供相同的内容时,产品列表是空的
{
"ProductAdd": {
"Products": [
{
"ProductInformation": { "ProductName": "Seahorse Necklace" }
},
{
"ProductInformation": { "ProductName": "Ping Pong Necklace" }
}
]
}
}
当另一个对象中有一个对象数组时,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/