【问题标题】:WCF Service parse JSON as Dictionary<string,string>()WCF 服务将 JSON 解析为 Dictionary<string,string>()
【发布时间】:2015-11-13 14:31:59
【问题描述】:

我有一整套接收 POST JSON 对象并回复其他 JSON 格式数据的 WCF Web 服务。

在服务中的一个特定方法中,我试图传递一个 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\"}}"

为什么不将其解析为字典?

【问题讨论】:

    标签: c# json ajax wcf


    【解决方案1】:

    我最终放弃了这个并创建了一个 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# 中使用正确的字典会很好,但是......你不能拥有一切。

    【讨论】:

      猜你喜欢
      • 2013-08-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-07
      • 1970-01-01
      相关资源
      最近更新 更多