2011-05-08 64 views
2

當調用「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

+0

我遇到過相同的行爲,即:對於實現接口的對象,接口上的JsonProperty屬性被忽略。如果上述工作,這將是很好的。 – Frank 2011-05-09 17:42:17

+0

我在猜測沒有人可以解決問題(簡單的解決方法)如果我有機會,我會下載源代碼,看看是否有可能/涉及修復它/上傳補丁 – 2011-05-10 07:09:05

回答

2

這已經被固定在由詹姆斯Json.NET代碼庫和工作。 查看codeplex issue report

+0

鏈接不管用。你能否幫助再次提供工作鏈接? – 2017-03-27 06:42:43

+0

@SankarBalasubramanian剛剛檢查了鏈接,它仍然有效 – 2017-03-27 07:29:44