views:

26

answers:

1

I am wondering whether I can use DataContractJsonSerializer to serialize a Structure type, or does it have to be a reference/Class type?

I have the following code:

<Extension()> Public Function ToJSON(ByVal target As Object) As String
    Dim serializer = New System.Runtime.Serialization.Json.DataContractJsonSerializer(target.GetType)
    Using ms As MemoryStream = New MemoryStream()
        serializer.WriteObject(ms, target)
        ms.Flush()

        Dim bytes As Byte() = ms.GetBuffer()

        Dim json As String = Encoding.UTF8.GetString(bytes, 0, bytes.Length).Trim(Chr(0))

        Return json
    End Using
End Function

And yet if I call it on a Structure type, such as a KeyValuePair(Of T1, T2), I get the following error:

Public member 'ToJSON' on type 'KeyValuePair(Of String,Object)' not found.

+2  A: 

The error message does not have anything to do with DataContractJsonSerializer or anything inside your method. It cannot find the method itself. That suggests to me that you have forgotten to add a reference to the namespace in which this extension method is defined. I apologise I don’t know the VB equivalent, but in C# it is the using clause I’m talking about.

Timwi
Hmm... odd. You are correct, that was the problem. This did teach me something else I didn't realize though. The extension was a public function in a public module in a DLL. I had the DLL/namespace imported to my aspx.vb file by means of an `Import` statement at the top of the file, and I was getting this error. I added the same import as a `\system.web\pages\namespaces` import in the web.config and then it worked fine. Apparently in ASP.NET you need to import your namepaces via web.config, NOT via Import statements in the VB file? Odd.
eidylon