1

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?

Masoud
  • 8,020
  • 12
  • 62
  • 123
  • @dbc: you are right, my question code run without problem, but I forgot to add some attributes to my code(`[DataContract]`, `[DateMember]`,`[Serialization]`), I updated my question. – Masoud Jul 20 '19 at 07:16
  • OK then duplicate of [caliburn.micro serialization issue when implementing PropertyChangedBase](https://stackoverflow.com/q/29200648): you need to add `[DataContract]` and `[DataMember]` attributes to the derived class if they're present on the base. – dbc Jul 20 '19 at 07:18
  • 1
    @dbc: Now my code works like a charm, thank you, – Masoud Jul 20 '19 at 07:34

0 Answers0