Given the following declaration:
<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.ToArray()
Dim json As String = Encoding.UTF8.GetString(bytes, 0, bytes.Length)
Return json
End Using
End Function
And the following lines in the Page_Load of a test page:
Dim kvp = New System.Collections.Generic.KeyValuePair(Of String, Object)(
"date", New HttpCookie("woot", "yikes")
)
Put(New HttpCookie("woot", "yikes").ToJSON)
Put(kvp.ToJSON)
Put(kvp.Value.ToJSON)
Put("here".ToJSON())
The first Put works perfect, and puts out the following JSON:
{"Domain":null,"Expires":"\/Date(-62135578800000-0500)\/",
"HttpOnly":false,"Name":"woot","Path":"\/",
"Secure":false,"Value":"yikes"}
The second Put, however, throws a giant, ugly error as so:
Type 'System.Web.HttpCookie' with data contract name 'HttpCookie:http://schemas.datacontract.org/2004/07/System.Web' is not expected. Consider using a DataContractResolver or add any types not known statically to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to DataContractSerializer.
The third Put throws an error also, but COMPLETELY different:
Public member 'ToJSON' on type 'HttpCookie' not found.
And the fourth Put works perfect.
I am very confused why, when the first line works, and the Extension method is clearly being found on the HttpCookie object, why then in the 2nd and 3rd Puts does it NOT work, and why do I get a different error in both cases? Each of the first three Puts is trying to do the same thing - call the ToJSON extension method on the HttpCookie object.
All exposition welcome!