list - Web API 使用附加属性扩展列表

标签 list generics asp.net-web-api

我喜欢在列表级别使用附加属性扩展项目列表。 这样我就可以给出List的名字,Paging信息等等。

这是列表的示例对象项:

public class House
{
    public int Nummer { get; set; }
    public string Name { get; set; }
}

这是我的简单列表类 - 具有一个附加属性:

public class SimpleList : List<House>
{
  public string MyExtraProperty { get; set; }
}

这是我的 Web Api Controller 方法:

public class ValuesController : ApiController
{
    // GET api/values
    public SimpleList Get()
    {
        SimpleList houseList = new SimpleList {};
        houseList.Add(new House { Name = "Name of House", Nummer = 1 });
        houseList.Add(new House { Name = "Name of House", Nummer = 2 });
        houseList.MyExtraProperty = "MyExtraProperty value";

        return houseList;
    }
}

结果以 XML 格式显示:

<ArrayOfHouse>
 <House><Name>Name of House</Name><Nummer>1</Nummer></House>
 <House><Name>Name of House</Name><Nummer>2</Nummer></House>
</ArrayOfHouse>

在 Json 中 [{"Nummer":1,"Name":"房屋名称"},{"Nummer":2,"Name":"房屋名称"}]

我的问题是如何让 MyExtraProperty 解析结果?

我的迷你演示解决方案在这里:https://dl.dropboxusercontent.com/u/638054/permanent/WebApiGenerics.zip

感谢您的帮助!

最佳答案

最简单的方法是让您的 List 成为 SimpleList 的成员而不是父类(super class)

public class SimpleList 
{
    public List<House> Houses;
    public string MyExtraProperty { get; set; }
}

如果您只需要 JSON,您可以通过装饰 Newtonsoft JSON 模型来自行控制序列化:

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace WebApiGenerics.Models
{
    [JsonObject(MemberSerialization = MemberSerialization.OptIn)]
    public class SimpleList : List<House>
    {
        [JsonProperty]
        public IEnumerable<House> Houses
        {
            get { return this.Select(x => x); }
        }

        [JsonProperty]
        public string MyExtraProperty { get; set; }
    }
}

关于list - Web API 使用附加属性扩展列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17490752/

相关文章:

java - 我可以在java中添加两个泛型值吗?

python - 将数字的数字写入数组

c# - DoublyLinkedList C# 移除最后两个元素

c# - 一个列表中的多个结构类型

java 泛型用于两种以上类型

java - 字符串无法转换为 T

c# - User 类是否应该实现 IPrincipal 和 IIdentity

asp.net-web-api - 使用 SimpleInjector 有没有办法用 .net 4/webapi 1 复制 RegisterWebApiRequest<T>()?

c# - Astra Datastax - Asp.net core - Secure Connect Bundle(Zip 文件)在本地工作但在发布到 Azure 应用程序服务时不工作

python - 在 bool 列表中获取 True 值的索引