我喜欢在列表级别使用附加属性扩展项目列表。 这样我就可以给出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/