简体   繁体   English

使用SignalR,如何向Javascript发送字典(关联数组)?

[英]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... 字典不可序列化,因此不能通过SignalR作为Javascript(伪)关联数组发送给我的客户端JavaScript代码...

in .net, my complex type is: 在.net中,我的复杂类型是:

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: 在Javascript中,我希望能够像这样引用数据:

data.Properties["key"]

Update: 更新:

I'm trying to serialize to and from a string first because I route the instance through SQL Service Broker. 我正在尝试先串行化一个字符串,因为我通过SQL Service Broker路由实例。 On this line: 在这一行:

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

Where T is typeof MyClass 其中T是MyClass的类型

There was an error reflecting type [MyClass] 反映类型[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. 无法序列化成员[MyClass] .Properties类型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]],因为它实现了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> . SignalR使用Json.NET,它绝对能够序列化Dictionary<string, string> You should be able to access the dictionary from JS code in the exact manner you suggest in your question. 您应该能够以您在问题中建议的确切方式从JS代码访问字典。

Have you tried sending an instance of your MyClass using SignalR? 您是否尝试过使用SignalR发送MyClass实例? 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...) (并处理一些命名空间问题......)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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