Search code examples
deserializationxmlreader

How do I Serialize/Deserialize a complex class? I only get the properties, no data in return


This looks stupid, I know, but still: when I deserialize from an XML object and convert to the desired class object, all I get is the (correct) objectstructure, but the values I need remain Nothing or Null (depends on the propery type of the Class definition.

I am VERY sure that the parameter XMLString that is used certainly contains data. The object structure is not retrieved from nowhere!

The Generic Object is not the problem, MyObject when it returns is of the correct type. But does anyone have any idea why the object contains no real data as there is in the XML?

Here's the code I use:

Public Shared Function ReadObjectFromXML(Of T)(XMLString As String) As T
    Dim MyObject As T

    Dim read As StringReader = New StringReader(XMLString)
    Dim serializer As New XmlSerializer(GetType(T))
    Dim reader As XmlReader = New XmlTextReader(read)

    Try
        MyObject = DirectCast(serializer.Deserialize(reader), T)
        Return MyObject

    Catch
        Return Nothing

    Finally
        reader.Close()
        read.Close()
        read.Dispose()
    End Try

End Function

Thanks!

Peter


Solution

  • The problem is probably not in the (de)serializer, but in the defintion of the ObjectClass.

    When an ObjectClass has a complex structure, that is, with properties that are in fact List(of T) items, then the ObjectClass definition should NOT have any xmltags preceding that property. All other properties should have the prefix.

    At least i my case, this solved (after two days of searching througout the web) my issue.

    Cheers!

    Peter