I wrote an extension method to serialize an object to JSON
using Json.NET
public static string ToJson(this object value)
{
if (value == null)
{
return string.Empty;
}
var settings = new JsonSerializerSettings
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
};
return JsonConvert.SerializeObject(value, Formatting.Indented, settings);
}
I have following classes
[Serializable]
[DataContract]
public class BaseEntity
{
[DataMember]
public int Id { get; set; }
}
[Serializable]
public class MyEntity: BaseEntity
{
public string Name { get; set; }
}
when I run following code
var myEntity = new MyEntity{
Id = 1,
Name = "test"
};
Console.WriteLine(myEntity.ToJson());
The output is
{ "Id": 1 }
but I expect
{
"Id": 1
"Name":"test"
}
when I comment [DataContract]
and [DataMember]
attributes the result is as expected, but with these attributes, not, where is the problem?