Remove <ArrayOf. From MVC Web Api response

拥有回忆 提交于 2020-01-01 04:25:15

问题


I am getting the following response from a standard MVC 4 WebApi project;

<ArrayOfProduct xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Product>
<Id>1</Id>
<Name>Tomato Soup</Name>
<Category>Groceries</Category>
<Price>1</Price>
</Product>
</ArrayOfProduct>

I am trying to make it so that it returns

<Products>
<Product>
<Id>1</Id>
<Name>Tomato Soup</Name>
<Category>Groceries</Category>
<Price>1</Price>
</Product>
</Products>

I have found many reference to various methods that supposedly solve this, none work;

Changing the default serializer does not work.

Creating a customer serializer for Product does not work.

Creating a new class that has List<Product> exposed with suitable XmlRoot and XmlElement attributes does not work.

Adding Datacontract attributes does not work.

Adding CollectionDatacontract attributes does not work.

This appears to be so simple to everyone else, except me!


回答1:


Try using the XmlSeriazlier instead:

config.Formatters.XmlFormatter.UseXmlSerializer = true;

And then try defining a class that derives from the collection of Product, and use [XmlRoot("Products")] to rename the element name from 'ArrayOfProduct' to 'Products'.

For example, instead of using List, use the class Products:

[XmlRoot("Products")]
public class Products : List<Product> { }

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Category { get; set; }
    public double Price { get; set; }
}

ApiController's action:

    public Products Get()
    {
        return new Products()
        {
            new Product() 
            {
                Id = 1,
                Name = "Tomato Soup", 
                Category = "Groceries",
                Price = 1
            }
        };
    }


来源:https://stackoverflow.com/questions/13056518/remove-arrayof-from-mvc-web-api-response

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!