简体   繁体   中英

Using SignalR, how do I send a dictionary (associative array) to Javascript?

dictionary isn't serializeable, and therefore can't be sent to my clients JavaScript code via SignalR as a Javascript (pseudo) associative array...

in .net, my complex type is:

public class MyClass {
   public [primitive] whatever {get;set;}
   ...
   public Dictionary<string, string> Properties { get; set; }
}

and in Javascript, I'd like to be able to reference the data like this:

data.Properties["key"]

Update:

I'm trying to serialize to and from a string first because I route the instance through SQL Service Broker. On this line:

XmlSerializer serializer = new XmlSerializer(typeof(T));

Where T is typeof MyClass

There was an error reflecting type [MyClass]

Cannot serialize member [MyClass].Properties of type System.Collections.Generic.Dictionary`2[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], because it implements IDictionary.

I feel like I'm about to answer my own question...

SignalR uses Json.NET which is definitely able to to serialize a Dictionary<string, string> . You should be able to access the dictionary from JS code in the exact manner you suggest in your question.

Have you tried sending an instance of your MyClass using SignalR? If so, how does it fail?

I changed:

XmlSerializer serializer = new XmlSerializer(typeof(T));

to:

DataContractSerializer serializer = new DataContractSerializer(typeof(T));

(and dealt with some namespace issues...)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM