Using JSON.NET, how do I serialize these inherited elements?

I have the following:

public class MyClass : SuperClass { [JsonProperty] public virtual string Id { get; set; } } public abstract class SuperClass { public int GetHashCode() { //do things here } } 

I can not change SuperClass . When I move on to serializing Json using JsonNet, I will do something like this:

  JsonSerializerSettings serializer = new JsonSerializerSettings { //serializer settings }; var jsonNetResult = new JsonNetResult { Data = myClass, SerializerSettings = serializer }; return jsonNetResult; 

Obviously, this will not be serialized by GetHashCode() . If I go:

  var jsonNetResult = new JsonNetResult { Data = myClass.GetHashCode(), SerializerSettings = serializer }; 

It serializes the value correctly, is there some kind of serialization parameter that I can use to tell it to include GetHashCode() ?

Edit: I have to add that right now I'm only creating a property for this, i.e.

 [JsonProperty] public virtual int GetHashCodeJson { get { return GetHashCode(); } 
+4
source share
1 answer

This is not so much a problem with JSON.Net as with serialization of .net in general.

You need to serialize objects by their properties, and you are requesting serialization of the return value of the method. Therefore, you cannot do this with the syntax you want.

What you can do is:

 Data = myClass.GetHashCode() 

It only means that the return value of the method (int) can be serialized, and not that the serializer does not care at all about which method uses this value.

If you think about it, it makes no sense to say that the value is the serialized return value of the method, because how do you then deserialize it? You can never write a value back to a method because it only has a return value, not a two-way relationship, such as a property with {get; set;}.

0
source

All Articles