1

Entity objects needs converted to string to store them in log file for human reading. Properties may added to derived entities at runtime. Serialize is defined in entity base class. I triesd code below but it returns properties with null values also. Since many properties have null values, it makes logs difficult to read.

Hoq to serialize only not-null properties ? I tried also

        var jsonSettings = new JsonSerializerSettings()
        {
            DefaultValueHandling = DefaultValueHandling.Ignore,
            Formatting = Formatting.Indented,
            TypeNameHandling= TypeNameHandling.All
        };
        return JsonConvert.SerializeObject(this, GetType(), jsonSettings);

this serializes only EntityBase class properties as confirmed in newtonsoft json does not serialize derived class properties

public class EntityBase {

        public string Serialize()
        {
            var s = new System.Web.Script.Serialization.JavaScriptSerializer();
            s.Serialize(this);

        }
     }

public class Customer: EntityBase {
  public string Name, Address;
  }

testcase:

  var cust= new Customer() { Name="Test"};
  Debug.Writeline( cust.Serialize());

Observed: result contains "Address": null

Expected: result shoud not contain Address property.

ASP.NET/Mono MVC4, .NET 4.6 are used

Community
  • 1
  • 1
Andrus
  • 26,339
  • 60
  • 204
  • 378
  • this might help you http://stackoverflow.com/questions/8513042/json-net-serialize-deserialize-derived-types – ltiveron Oct 07 '16 at 14:19
  • I tried `TypeNameHandling= TypeNameHandling.All` according to this. Also tried to pass type ussing `JsonConvert.SerializeObject(this, GetType(), jsonSettings)` but child class properties are still not serialized. – Andrus Oct 07 '16 at 14:49
  • What do you mean by *Properties may added to derived entities at runtime.*? Do you really mean *runtime*? If so, is your base class inheriting from `ExpandoObject` or something similar? – dbc Oct 07 '16 at 17:15
  • Json.NET seems to work fine. `Name` is serialized while `Address` is not. See https://dotnetfiddle.net/Xljh8U – dbc Oct 07 '16 at 17:28
  • Your fiddle works OK but in MVC controller similar code does not return any property. No idea why – Andrus Oct 07 '16 at 21:27

1 Answers1

7

You can create your own serializer to ignore null properties.

            JsonConvert.SerializeObject(
                object, 
                Newtonsoft.Json.Formatting.None, 
                new JsonSerializerSettings
                {
                    NullValueHandling = NullValueHandling.Ignore
                });
Robert L.
  • 1,469
  • 1
  • 11
  • 10