选项 1:使用自定义 ContractResolver
您可以创建自定义合同解析器并在创建响应时使用它:
public class TestContractResolver : DefaultContractResolver
{
public string ExcludeProperties { get; set; }
protected override IList<JsonProperty> CreateProperties(Type type,
MemberSerialization memberSerialization)
{
if (!string.IsNullOrEmpty(ExcludeProperties))
return base.CreateProperties(type, memberSerialization)
.Where(x => !ExcludeProperties.Split(',').Contains(x.PropertyName))
.ToList();
return base.CreateProperties(type, memberSerialization);
}
}
用法如下:
[HttpGet]
public HttpResponseMessage Test()
{
var person = new Person() { Id = 1, FirstName = "x", LastName = "y", Age = 20 };
string excludeProperties= "FirstName,Age";
string result = JsonConvert.SerializeObject(person, Formatting.None,
new JsonSerializerSettings
{
ContractResolver = new TestContractResolver()
{
ExcludeProperties = excludeProperties
}
});
var response = this.Request.CreateResponse(HttpStatusCode.OK);
response.Content = new StringContent(result, Encoding.UTF8, "application/json");
return response;
}
结果是:
{"Id":1,"LastName":"y"}
选项 2:使用字典
您可以忽略一个以逗号分隔的属性名称字符串,然后选择属性并将它们(名称和值)放入字典中并将它们用作结果:
[HttpGet]
public Dictionary<string, Object> Test()
{
var person = new Person() { Id = 1, FirstName = "x", LastName = "y", Age = 20 };
string excludeProperties = "FirstName,Age";
var dictionary = new Dictionary<string, Object>();
person.GetType().GetProperties()
.Where(x => !excludeProperties.Split(',').Contains(x.Name)).ToList()
.ForEach(p =>
{
var key = p.Name;
var value = p.GetValue(person);
dictionary.Add(key, value);
});
return dictionary;
}
结果是:
{"Id":1,"LastName":"y"}