WCF服务将JSON解析为Dictionary <string,string>()

时间:2015-11-13 14:31:59

标签: c# json ajax wcf

我有大量的WCF Web服务接收POST JSON对象并使用其他JSON格式的数据进行回复。

在服务中的一个特定方法中,我尝试传递JSON对象并将其解析为Dictionary()。

该方法的接口定义为:

[OperationContract(Name = "GetSomeData")]
[WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Wrapped, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
string GetSomeData(AuthenticationData authData, Dictionary<string, string> options, string srcHash);

并且方法声明本身是:

public string GetSomeData(AuthenticationData authData, Dictionary<string,string> options, string srcHash)
{
    // do something fancy
}

authData和srcHash是所有方法的标准参数,包含预期数据,正确解析为authData的AuthenticationData对象。

其他方法对于声明的对象和基元都可以正常工作,但是Dictionary总是空的。

发送的JSON字符串是:

"{\"options\",{\"id\":\"1\"}}"

为什么这不被解析为字典?

1 个答案:

答案 0 :(得分:0)

我最终放弃了这个并创建了一个List类来模拟字典。

[Serializable]
public class JSONDictionary
{
    [DataMember] public string _key;
    [DataMember] public string _value;
}

然后在客户端(Javascript):

client.utils.toJSONDictionary = function (obj)
{
    var dictionary = [];
    for (member in obj)
    {
        dictionary.push({ _key: member, _value: obj[member].toString() });
    }
    return dictionary;
}

这很好用。在c#中使用合适的字典会很好但是......你不能拥有一切。