Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ServiceStack - empty json when returning class

I have a very strange issue with ServiceStack when serialazing a class to JSON - objects are empty, however XML works fine.

Found some suggestion that, JSON serializer works only when properties are public, but as you can see below my properties are public.

Please see below the code and screenshots. Any suggestion are much appreciated.


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
like image 559
Iladarsda Avatar asked Jul 04 '13 11:07

Iladarsda


1 Answers

By default, ServiceStack will only serialize public properties, not public fields, in your DTOs. So you need to either declare username and fullname each as a property in your User class, or configure ServiceStack.Text to serialize fields (by setting JsConfig.IncludePublicFields to True).

Note that for JSON serialization ServiceStack.Text is used, while for XML serialization, the BCL XML serializer is used. Thus, the configuration and behavior of XML vs JSON serialization can differ in these sorts of ways with ServiceStack.

like image 175
Mike Mertsock Avatar answered Nov 19 '22 10:11

Mike Mertsock