3

I have hundreds of existing POCOs that I'm currently using with Entity Framework. A new requirement is that I need to be able to serialize these objects and cache them in Redis. I decided to serialize to JSON using Json.NET but it won't serialize all of my objects. See the example below.

public class Envelope<T>
{
    public string Metadata{ get; set; }
    public T Value { get; set; }
}

public class MyClass {
    public string MyProperty { get; set; }
}

public void Serialize()
{
    Envelope<List<MyClass>> envelope = new Envelope<List<MyClass>>();
    envelope.Metadata = "Some Metadata";
    envelope.Value.Add(new MyClass { MyProperty = "Some Property Data" });
    string json = JsonConvert.Serialize(envelope);
}

When this data structure is serialized, everything looks good except MyClass.MyProperty is ignored. The List<MyClass> becomes a JSON array with 1 element but that element has no properties. If I add [DataContract] and [DataMember] to MyClass, then they are serialized correctly. I shouldn't have to do this, right? I didn't have to put those attributes on the Envelope<T> class. I'd rather not have to go through my hundred of POCOs and add these attributes.

Raymond Saltrelli
  • 4,071
  • 2
  • 33
  • 52
  • 2
    I think there's something else going on in your code that your example above isn't capturing. The code above runs fine in [dotnetfiddle](https://dotnetfiddle.net/dvlMsQ) and produces an output that does include `MyProperty`. – Nate Barbettini Apr 18 '17 at 21:30
  • Which version of JSON.NET are you using? – Nate Barbettini Apr 18 '17 at 21:32
  • 1
    Json.Net does not require the use of `[DataContract]` or `[DataMember]`. In your code, is `MyProperty` public? If not, that would explain why it is ignored. – Brian Rogers Apr 18 '17 at 22:25
  • 1
    If, in your real code, `MyClass` inherits from a base class with `[DataContract]` applied, then `MyProperty` will not be serialized by Json.NET unless marked with `[DataMember]`. For a similar problem see [this question](http://stackoverflow.com/q/29200648) and [this closed Json.NET issue](https://github.com/JamesNK/Newtonsoft.Json/issues/603) – dbc Apr 18 '17 at 23:31
  • @dbc I think that is my problem. Some of my POCOs share a base class which has [DataContract]. – Raymond Saltrelli Apr 19 '17 at 12:55
  • Then possibly check out [Configure JSON.NET to ignore DataContract/DataMember attributes](https://stackoverflow.com/q/11055225/3744182). You may need to manually configure the resolver to ignore unwanted base class properties though. – dbc Apr 19 '17 at 16:52

0 Answers0