Scott Savage
Scott Savage

Reputation: 373

How do you Serialize an object that has does not have SerializableAttribute set

I was wondering if there was an object/function that works like XmlSerializer does - but that does not require the Serializable Attribute to be set.

Here's why: I have a third party object that I would like to extract the information in the public properties (including any collections).

And - of course - the following routine returns an error of:

There was an error reflecting type 'ThridPartyObject' 

because the object was not compiled with the [Serializable] attribute.

Public Sub SerialMe(ThridPartyObject as Object)
    Dim objStreamWriter As New StreamWriter("C:\Object.xml")
    Dim x As New XmlSerializer(ThridPartyObject.GetType)
    x.Serialize(objStreamWriter, ThridPartyObject)
    objStreamWriter.Close()
End Sub

Perhaps something that would iterate through all the public properties of the 3rd party object? (And the public properties of those properties - and so on)

Any ideas?

Upvotes: 0

Views: 177

Answers (1)

djv
djv

Reputation: 15774

You can use reflection to access properties and fields by string name

Imports System.Reflection

Module Module1
    Sub Main()
        Dim c1 As New class1 With {.prop1 = 6, .field1 = 7}
        Console.WriteLine(c1.GetType().GetProperty("prop1").GetValue(c1, Nothing))
        Console.WriteLine(c1.GetType().GetField("field1").GetValue(c1))
    End Sub
End Module

Class class1
    Public Property prop1 As Integer
    Public field1 As Integer
End Class

Upvotes: 0

Related Questions