【问题标题】:Getting SerializeObject to use JsonProperty "name" defined inside interface让 SerializeObject 使用接口内定义的 JsonProperty“名称”
【发布时间】: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


【解决方案1】:

这个问题现在已经由 James 在 Json.NET 代码库中修复并且正在运行。 请参阅codeplex issue report 以及Json.NET 4.0 Release 3 release notes

新功能 - JsonObject 和 JsonProperty 属性现在可以放置在接口上,并在序列化实现对象时使用。

【讨论】:

  • 链接失效。您能否再次提供工作链接?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-22
  • 1970-01-01
  • 1970-01-01
  • 2021-07-03
  • 2019-09-14
  • 2017-11-20
相关资源
最近更新 更多