简体   繁体   English

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

[英]WCF Service parse JSON as Dictionary<string,string>()

I have a whole load of WCF web services that receive POST JSON objects and reply with other JSON formatted data. 我有一整套WCF Web服务,它们接收POST JSON对象并以其他JSON格式的数据进行回复。

In one particular method within a service I'm trying to pass a JSON object through and parse it as a Dictionary(). 在服务中的一种特定方法中,我试图通过JSON对象并将其解析为Dictionary()。

The interface to the method is defined as: 该方法的接口定义为:

[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);

and the method declaration itself is: 方法声明本身是:

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

the authData, and srcHash are standard parameters on all the methods and contain the expected data, correctly parsed as an AuthenticationData object for authData. authData和srcHash是所有方法上的标准参数,并且包含正确解析为authData的AuthenticationData对象的预期数据。

Other methods work perfectly fine for both declared objects and primitives however the Dictionary is always empty. 对于声明的对象和基元,其他方法都可以正常工作,但是Dictionary始终为空。

The JSON string being sent through is: 通过发送的JSON字符串是:

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

Why is this not being parsed as a Dictionary? 为什么不将其解析为字典?

I eventually gave up on this and created a List class to simulate a dictionary. 我最终放弃了这一点,创建了一个List类来模拟字典。

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

Then on the client side (Javascript): 然后在客户端(JavaScript):

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

And that works fine. 那很好。 Would be nice to use a proper dictionary in c# but... well you can't have everything. 在c#中使用适当的字典会很好,但是...嗯,您不可能拥有一切。

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

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