0

我在 WebAPI 控制器中有一个模型和一个动作

public class MyModel 
{
    public ClassA ObjA { get; set; }
    public ClassB ObjB { get; set; }
    public ClassC ObjC { get; set; }
} 

和行动:

[HttpGet]
public MyModel GetMyModel()
{
    MyModel result = someMethod();

    return result;
}

其中某些属性result可能为空。我知道我可以[JsonIgnore]用来忽略序列化的属性,但我希望它是动态的,并且取决于从someMethod(). 是否可以只返回那些不在nullMVC4 .net 中的 JSON 中的属性,以便客户端不会"ObjA": null在响应中得到类似的东西?基本上我想对客户隐藏一些他们不需要关心的属性。

4

1 回答 1

0

You can get the list of properties on your object with the following:

PropertyInfo[] properties = result.GetType().GetProperties();

You can then iterate through the list of properties, and create a key/value collection which contains only those that are not null.

var notNullProperties = new Dictionary<string, object>();
foreach (PropertyInfo property in properties) 
{
    object propertyValue = property.GetValue(result, null);
    if (propertyValue != null) 
    {
        notNullProperties.Add(property.Name, propertyValue);
    }
 }

And then return the serialized dictionary.

于 2014-04-02T00:13:18.703 回答