2013-07-04 31 views
5

當將一個類序列化爲JSON時,ServiceStack中存在一個非常奇怪的問題 - 對象爲空,但是XML工作正常。ServiceStack - 返回類時的空JSON

發現了一些建議,JSON序列化程序只在屬性公開時才起作用,但正如您在下面看到的,我的屬性是公開的。

請參閱下面的代碼和截圖。任何建議都非常感謝。


XML enter image description here
JSON enter image description here
GetUsers.aspx.vb

Public Class GetUsersAD 

     Public Property username As String 
     Public Property fullname As String 


     Public Function HandleRequest() 

       Dim _users As New List (Of User) 
      _users = GetUsersTest(_users) 
       Return _users 

     End Function 

     Public Function GetUsersTest(_users As List (Of User)) As List (Of User) 

       Dim dt As New DataTable 
      dt.Columns.Add("username") 
      dt.Columns.Add("fullname") 

       For x As Integer = 0 To 5 

        Dim newUserRow As DataRow = dt.NewRow() 
        newUserRow("username") = "username-" & x & "" 
        newUserRow("fullname") = "fullname-" & x & "" 
        dt.Rows.Add(newUserRow) 

       Next 

       For Each row As DataRow In dt.Rows 

        Dim _user As New User 
        _user.username = row("username") 
        _user.fullname = row("fullname") 
        _users.Add(_user) 

       Next 


       Return _users 

     End Function 

End Class 

Public Class User 

     Public username As String = "" 
     Public fullname As String = "" 


End Class 

Public Class Users 

     Public username As String = "" 
     Public fullname As String = "" 


End Class 

WS.vb

Public Class WrapperGetUsers 

    Implements IService(Of GetUsersAD) 

    Public Property username As String 
    Public Property fullname As String 

    Public Function Execute(ByVal request As GetUsersAD) As Object Implements ServiceStack.ServiceHost.IService(Of GetUsersAD).Execute 

     Return request.HandleRequest() 

    End Function 


End Class 

回答

9

默認情況下,ServiceStack只會序列化的公共性能,不公開領域,在你的DTO。因此,您需要在User類中聲明usernamefullname各爲property,或者將ServiceStack.Text配置爲序列化字段(將JsConfig.IncludePublicFields設置爲True)。

請注意,對於JSON序列化,使用ServiceStack.Text,而對於XML序列化,使用BCL XML序列化程序。因此,使用ServiceStack以XML和JSON序列化的配置和行爲可以以這些方式不同。

+0

一旦'公共屬性添加到用戶類'一切正常。謝謝你的提示。 – Iladarsda

+1

另外,看起來你可以從'GetUsersAD'和'WrapperGetUsers'類中移除這些屬性,除非你將它們用於其他目的。基本上,不要把你想要的屬性放在你的服務類中的請求/響應中,把它們放在單獨的DTO類(比如你的'User'類)中。 –

+0

我不確定我應該放置哪些屬性,所以我在任何地方都使用它們。謝謝你的提示。 – Iladarsda