Getting SerializeObject to use JsonProperty “name” defined inside interface

我的梦境 提交于 2019-12-04 04:16:59

问题


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());
    ...
    ...
}

UPDATE: Reported on Codeplex project site


回答1:


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:

New feature - JsonObject and JsonProperty attributes can now be placed on an interface and used when serializing implementing objects.



来源:https://stackoverflow.com/questions/5929342/getting-serializeobject-to-use-jsonproperty-name-defined-inside-interface

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!