当调用“JsonConvert.SerializeObject”时,我传入一个实现接口的对象。它是定义JsonProperty属性以设置所需的JSON对象属性名称的接口。但是,当我检查生成的JSON对象时,它使用的是实际的.NET属性名称,而不是JsonPropertyAttribute值。这让我相信它只反映了接口的实现来查找JsonProperty属性,而不是接口本身。我已经验证,如果我将JsonProperty属性放在实现类上,那么一切都按预期工作,但这不是所需的行为。有没有什么办法可以让JSON.NET获取界面上定义的JsonPropertyAttributes以及界面的界面(或替代界面)。获取SerializeObject使用接口内定义的JsonProperty“名称”
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());
...
...
}
UPDATE:报道称,Codeplex project site
我遇到过相同的行为,即:对于实现接口的对象,接口上的JsonProperty属性被忽略。如果上述工作,这将是很好的。 – Frank 2011-05-09 17:42:17
我在猜测没有人可以解决问题(简单的解决方法)如果我有机会,我会下载源代码,看看是否有可能/涉及修复它/上传补丁 – 2011-05-10 07:09:05