Unable to return dictionary (Of String, String) using GET ajax web request, works with POST

I have the following web method:

<WebMethod()> _ <ScriptMethod(ResponseFormat:=ResponseFormat.Json, UseHttpGet:=True, XmlSerializeString:=True)> _ Public Function GetDictionary() As Dictionary(Of String, String) Dim d As New Dictionary(Of String, String) d.Add("key1", "value1") d.Add("key2", "value2") Return d End Function 

I can get the results in order (JSON) if I use HttpPost from my ajax call, but as soon as I use HttpGet, I get the following exception:

System.NotSupportedException: type System.Collections.Generic.Dictionary`2 [[System.String, mscorlib, Version = 2.0.0.0, Culture = neutral, PublicKeyToken = b77a5c561934e089], [System.String, mscorlib, Version = 2.0.0.0, Culture = neutral, PublicKeyToken = b77a5c561934e089]] is not supported because it implements IDictionary

I wanted to use HttpGet here so that the result can be cached.

I tried all the options for calling this, but no luck. Any ideas? Is this possible with GET?

0
source share
2 answers

I got a little confused - if ResponseFormat is JSON (as in your example above), then I need to support derived IDictionary, however if it's XML, then I could understand by seeing this error, because XmlSerializer does not support this.

One way to send a dictionary type using XmlSerializer is to implement logic to convert it to an array or List or ArrayList. Alternatively, you can implement a custom serializer for data and write your own XML, instead returning an XmlDocument from your method. This will allow you to format the data in any way.

Maybe you can clarify if you use JSON or XML?

+1
source

Another alternative is to change the Return type to String, and then convert the dictionary to JSON through JavaScriptSerializer.Serialize . Perhaps this is not exactly what you intended with the return of the Dictionary, but it will be key = value pairs in the JSON response.

 <WebMethod()> _ <ScriptMethod(ResponseFormat:=ResponseFormat.Json, UseHttpGet:=True, XmlSerializeString:=True)> _ Public Function GetDictionary() As String Dim d As New Dictionary(Of String, String) d.Add("key1", "value1") d.Add("key2", "value2") Return New JavaScriptSerializer().Serialize(d) End Function 

And the resulting JSON:

 {"key1":"value1","key2":"value2"} 
+1
source

All Articles