2

Closed

Doesn't read JsonProperty values defined on interfaces

description

Hi,
 
I have an object that implements an interface and have decorated the interface with the JsonPropertyAttribute. When deserialising JSON into the object the framework doesn't work as desired, rather than using the attributes defined on the interface it attempts to deserialise using the classes property name.
 
So given the rough code below:
 
interface ITest
{
[JsonProperty("JsonValue")]
string Value{ get; set; }
}
 
public class Test : ITest
{
public string Value { get; set; }
}
 
If you attempt to deserialise the JSON "{JsonValue: 'Me' }" and cast it to "Test" the Value property will be null. If however you decorate the actual property in Test (rather or as well as ITest) then it will contain the value 'Me'.
 
Stepping through the code I see it is the line below (ln 684 of DefaultContractResolver) that causes the issue. This call will return null if there is no JsonPropertyAttribute on the concrete implementation of the property. What would be needed in the code to default through to reflect against implemented interfaces if no attribute can be found on the class instance? Ideally the line below will check the concrete instance of the class pointed to by "member" and then if that doesn't find an attribute it will try any implemented interface.
 
JsonPropertyAttribute propertyAttribute = JsonTypeReflector.GetAttribute<JsonPropertyAttribute>(member);
Closed May 21, 2011 at 1:57 PM by JamesNK
Added

comments

Paul_Hadfield wrote Jun 12, 2011 at 7:22 AM

Thanks James, Just downloaded and built code from trunk and verified that attributes are now being picked up when defined in an interface - great stuff.

There is currently an open question on Stack Overflow when I first noticed this, if you want to answer it and link back to this fix, then I'll mark it as the accepted answer: http://stackoverflow.com/questions/5929342/getting-serializeobject-to-use-jsonproperty-name-defined-inside-interface