Oliver Oliver - 1 year ago 47
Vb.net Question

Deserialize Json to Object in a constructor

I have an Object representing an entity and I would like to have a constructor with a JSON string as parameter representing the Object instead of having a JsonUtils (or whatever) to desearialize.

Imports System.Web.Script

Public Class Person

Public Property Age As Integer
Public Property Children As Integer
Public Property Married As Boolean

Public Sub New()
End Sub

Public Sub New(ByVal sJson as String)
Dim serializer As New Serialization.JavaScriptSerializer
Me = serializer.Deserialize(Of Person)(sJson)
End Sub

End Class

Of course I can't set Me because compiler throws an error "'Me' no puede ser el destino de una asignaciĆ³n" ("'Me' can not be the target of an assignment", sorry but my VS2005 is in spanish).

How can I achieve this?
Is this approach the right way?

Enviroment: Visual Studio 2005, .net Framework 2.0 (not possible to update)

Answer Source

The simplest thing is simply to let the serializer create the new object:

 Dim p As Person = serializer.Deserialize(Of Person)(sJson)

To keep the deserializtion code in the class, you could use a shared method to create the new object:

Public Shared Function FromJson(ByVal sJson As String) As Person
    Dim serializer As New Serialization.JavaScriptSerializer
    Return serializer.Deserialize(Of Person)(sJson)
End Function


Dim p As Person = Person.FromJson(sJson)

It is not all that different from the syntax for self-deserialization:

Dim p As Person = New Person(sJson)

Finally, you could copy each property from a deserialized temp var to Me.Age etc. But whether property by property or thru Reflection, this seems needlessly complex for what you describe.