tags:

views:

97

answers:

1

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 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(); }
A: 

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;}.

jarrett
Well a way around it is to have a property without a get and no set, that references the method, which works fine. Is there a better way of dealing with it than that? Then you get convoluted properties like GetHashCodeJson { get { return GetHashCode(); } }
chum of chance
I agree the name isn't so good. In your case it could just be HashCode instead of GetHashCodeJson if you wanted to do that, but the problem remains the same, you need a different name for the property than the method.
jarrett