如何从WCF REST方法返回自定义类型值的Dictionary作为常规JSON对象?

假设我有一个看起来像这样的自定义类型:

[DataContract] public class CompositeType { [DataMember] public bool HasPaid { get; set; } [DataMember] public string Owner { get; set; } } 

和一个如下所示的WCF REST接口:

 [ServiceContract] public interface IService1 { [OperationContract] Dictionary GetDict(); } 

那么我如何让我的方法实现返回一个看起来像这样的JSON对象…

 {"fred":{"HasPaid":false,"Owner":"Fred Millhouse"},"joe":{"HasPaid":false,"Owner":"Joe McWirter"},"bob":{"HasPaid":true,"Owner":"Bob Smith"}} 

希望它看起来像这样:

 [{"Key":"fred","Value":{"HasPaid":false,"Owner":"Fred Millhouse"}},{"Key":"joe","Value":{"HasPaid":false,"Owner":"Joe McWirter"}},{"Key":"bob","Value":{"HasPaid":true,"Owner":"Bob Smith"}}] 

理想情况下,我宁愿不必改变方法的返回类型。

我尝试了很多不同的方法,但找不到有效的解决方案。 令人讨厌的是,使用Newtonsoft.Json在一行中生成正确形状的JSON对象结构很容易:

 string json = JsonConvert.SerializeObject(dict); 

其中dict定义为:

 Dictionary dict = new Dictionary(); dict.Add("fred", new CompositeType { HasPaid = false, Owner = "Fred Millhouse" }); dict.Add("joe", new CompositeType { HasPaid = false, Owner = "Joe McWirter" }); dict.Add("bob", new CompositeType { HasPaid = true, Owner = "Bob Smith" }); 

但我不想从我的WCF方法返回一个字符串。 这是因为它隐藏了返回的真实类型; 而且因为WCF也序列化了字符串,导致转义双引号和其他丑陋,使得非.Net REST客户端难以解析。

这是响应@dbc评论的部分解决方案。 它导致了这种形状正确的JSON结构……

 {"fred":{"HasPaid":false,"Owner":"Fred Millhouse"},"joe":{"HasPaid":false,"Owner":"Joe McWirter"},"bob":{"HasPaid":true,"Owner":"Bob Smith"}} 

但不幸的是,必须将方法的返回类型更改为Message 。 界面变为:

 [ServiceContract] public interface IService1 { [OperationContract] Message GetDict(); } 

并且实现变为:

 using Newtonsoft.Json; ... [WebGet(ResponseFormat = WebMessageFormat.Json)] public Message GetDict() { Dictionary dict = new Dictionary(); dict.Add("fred", new CompositeType { HasPaid = false, Owner = "Fred Millhouse" }); dict.Add("joe", new CompositeType { HasPaid = false, Owner = "Joe McWirter" }); dict.Add("bob", new CompositeType { HasPaid = true, Owner = "Bob Smith" }); string json = JsonConvert.SerializeObject(dict); return WebOperationContext.Current.CreateTextResponse(json, "application/json; charset=utf-8", Encoding.UTF8); } 

需要注意的一个有用function是,与返回Stream时不同,当您访问REST方法的URI时, 可以在Web浏览器中轻松查看JSON。