开发者

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

I have the following:

public class MyClass : SuperClass {    
  [JsonProperty]
  public virtu开发者_StackOverflowal string Id { get; set; }
}

public abstract class SuperClass { 
  public int GetHashCode() {
  //do things here
  }
}

I cannot alter SuperClass. When I go to serialize to Json using JsonNet I'll do something like this:

    JsonSerializerSettings serializer = new JsonSerializerSettings {
        //serializer settings
    };

    var jsonNetResult = new JsonNetResult {
        Data = myClass,
        SerializerSettings = serializer
    };

    return jsonNetResult;

Obviously it will not serialize GetHashCode(). If I go:

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

It will correctly serialize the value, is there some serializer setting I can use to tell it to include GetHashCode()?

Edit: I should add that right now I'm creating a property with only get to accomplish this, i.e.

[JsonProperty]
public virtual int GetHashCodeJson { get { return GetHashCode(); }


This is not so much an issue with JSON.Net as with .net serialization in general.

You need to serialize objects by their properties and you are asking to serialize the return value of a method. So there is not a way to do this with the syntax you want.

That you are able to do this:

Data = myClass.GetHashCode()

Only means that the return value of the method (an int) can be serialized and not that the serializer cares at all about what method that value is coming from.

If you think about it, there is not a lot of sense to saying that a value is the serialized return value of a method because how do you deserialize that then? You would never be able to write the value back to the method because its a return value only, not a 2-way relationship like a property with {get;set;}.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜