【发布时间】:2011-05-08 18:22:05
【问题描述】:
当调用“JsonConvert.SerializeObject”时,我传入了一个实现接口的对象。它是定义 JsonProperty 属性以设置所需 JSON 对象属性名称的接口。但是,当我检查生成的 JSON 对象时,它使用的是实际的 .NET 属性名称,而不是 JsonPropertyAttribute 值。这让我相信它只是反映接口的实现来查找 JsonProperty 属性,而不是接口本身。我已经验证,如果我将 JsonProperty 属性放在实现类上,那么一切都会按预期工作,但这不是所需的行为。有什么方法可以让 JSON.NET 获取接口上定义的 JsonPropertyAttributes 以及(或代替)接口。
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 project site
【问题讨论】:
-
我也遇到过同样的行为,即:接口上的 JsonProperty 属性对于实现接口的对象会被忽略。如果上述方法可行,那就太好了。
-
我猜没有人有修复(简单的出路)如果我有机会我会下载源代码,看看是否有可能/修复它会涉及什么/ 上传补丁
标签: json.net