问题描述
当调用"JsonConvert.SerializeObject"时,我传入的是实现接口的对象.它是定义JsonProperty属性的接口,以设置所需的JSON对象属性名称.但是,当我检查生成的JSON对象时,它使用的是实际的.NET属性名称,而不是JsonPropertyAttribute值.这使我相信,它只反映了接口的实现以查找JsonProperty属性,而不是接口本身.我已经验证了,如果我将JsonProperty属性放在实现类上,那么一切都会按预期进行,但这不是期望的行为.有什么方法可以使JSON.NET拾取在接口以及(或代替接口)上定义的JsonPropertyAttributes.
When calling "JsonConvert.SerializeObject" I am passing in an object that implements an interface. It is the interface that defines the JsonProperty attributes to set the desired JSON object property name. However when I examine the JSON object that is produced it is using the actual .NET property name, rather than JsonPropertyAttribute value. This leads me to believe it is only reflecting over the implementation of the interface to find the JsonProperty attributes, rather than the interface itself. I have verified that if I place the JsonProperty attributes on the implementing class then everything works as expected, but this is not the desired behaviour. Is there any way to make JSON.NET pick up the JsonPropertyAttributes defined upon the interface as well as (or instead of) the interface.
public interface ISpecifyDataPageToGet
{
[JsonProperty("offset")]
int PageNumber { get; }
[JsonProperty("limit")]
int PageSize { get; }
}
public class PageInfo : ISpecifyDataPageToGet
{
public PageInfo(int pageNumber, int pageSize)
{
this.PageNumber = pageNumber;
this.PageSize = pageSize;
}
// I don't want to have to define JsonProperty attribute here
public int PageNumber { get; private set; }
// Or here
public int PageSize { get; private set; }
}
public void MakeCall(ISpecifyDataPageToGet requestMessage)
{
// I'm passing instance of interface in here, but it still only picks up
// attributes defined on class implementing interface.
JsonConvert.SerializeObject(requestMessage, Formatting.None, new JsonSerializerSettings());
...
...
}
更新:报告于 Codeplex项目站点
推荐答案
James现在已在Json.NET代码库中修复了此问题,并且可以正常工作.请参见 codeplex问题报告以及 Json.NET 4.0 Release 3发行说明:
This has now been fixed in the Json.NET codebase by James and is working.See the codeplex issue report as well as the Json.NET 4.0 Release 3 release notes:
这篇关于获取SerializeObject以使用JsonProperty“名称"在接口内部定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!