سؤال

I have a model and an action in a WebAPI controller

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

and the action:

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

    return result;
}

where some properties in result could be null. I know that I could use [JsonIgnore] to ignore property for serialization but I want this to be dynamic and depending on the data from that were returned from someMethod(). Is it possible to only return those properties that aren't null in JSON in MVC4 .net so that the client won't get something like "ObjA": null in the response? Basically I wanted to hide some properties from the client that they don't need care about.

هل كانت مفيدة؟

المحلول

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.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top