2017-03-17 34 views
0

我正在使用ASP.NET Web API返回自定義類對象。該類有幾個屬性,其中一個採用可選參數。除了具有可選參數的屬性之外的所有屬性都可用於生成的JSON響應中。如果我刪除可選參數,則其他屬性也可以使用。任何方式來返回其他屬性的可選參數?謝謝!ASP.NET Web API - 返回對象 - 屬性丟失

這是我遇到的麻煩的特定屬性:

Public Class customer 

... 

Public ReadOnly Property photoSrc(Optional shape As String = Nothing) As String 
     Get 
      Dim srcString = "/Images/User.png" 
       If shape = "square" Then 
        srcString = "/Images/UserSquare.png" 
       End If 
      Return srcString 
     End Get 
    End Property 

... 

End Class 

,這裏是我使用返回JSON API的控制器功能:

Public Function GetCustomer(id As Integer) As Object 
    Dim customer As customer = New customer(id) 
    Return customer 
End Function 
+0

這真的很難確切地知道什麼樣的問題,你遇到不給我們提供了一種複製問題 –

回答

0

的屬性與參數稱爲索引屬性索引器。根據設計,即使索引參數是可選的,Json.Net(Web API用於JSON序列化)也不會序列化索引屬性。 (你可以在source code看到自己的DefaultContractResolver類的GetSerializableMembers方法。)

最簡單的解決方法是添加一個單獨的非索引屬性向類中調用你想要的參數值索引有序列化時。如果你願意的話,你可以讓這個房產變得私人如果你這樣做,你只需要用<JsonProperty>屬性標記它以允許串行器「看到」它。您還可以使用此屬性爲JSON中的備用屬性指定與其替換的索引屬性相同的名稱。

Public Class Customer 

    ... 

    <JsonProperty("photoSrc")> 
    Private ReadOnly Property defaultPhotoSrc As String 
     Get 
      Return photoSrc() 
     End Get 
    End Property 

    Public ReadOnly Property photoSrc(Optional shape As String = Nothing) As String 
     Get 
      Dim srcString = "/Images/User.png" 
      If shape = "square" Then 
       srcString = "/Images/UserSquare.png" 
      End If 
      Return srcString 
     End Get 
    End Property 

    ... 

End Class 

小提琴:https://dotnetfiddle.net/ffNs9D

+0

謝謝!這幫了大忙! –

相關問題