假设我有一个如下所示的自定义类型:
[DataContract]
public class CompositeType
{
[DataMember]
public bool HasPaid
{
get;
set;
}
[DataMember]
public string Owner
{
get;
set;
}
}
Run Code Online (Sandbox Code Playgroud)
和一个 WCF REST 接口,如下所示:
[ServiceContract]
public interface IService1
{
[OperationContract]
Dictionary<string, CompositeType> GetDict();
}
Run Code Online (Sandbox Code Playgroud)
那么我如何实现该方法以返回一个如下所示的 JSON 对象...
{"fred":{"HasPaid":false,"Owner":"Fred Millhouse"},"joe":{"HasPaid":false,"Owner":"Joe McWirter"},"bob":{"HasPaid":true,"Owner":"Bob Smith"}}
Run Code Online (Sandbox Code Playgroud)
我不希望它看起来像这样:
[{"Key":"fred","Value":{"HasPaid":false,"Owner":"Fred Millhouse"}},{"Key":"joe","Value":{"HasPaid":false,"Owner":"Joe McWirter"}},{"Key":"bob","Value":{"HasPaid":true,"Owner":"Bob Smith"}}]
Run Code Online (Sandbox Code Playgroud)
理想情况下,我不想改变方法的返回类型。
我尝试了许多不同的方法,但找不到有效的解决方案。令人烦恼的是,很容易用一行代码生成正确形状的 JSON 对象结构Newtonsoft.Json:
string json = JsonConvert.SerializeObject(dict);
Run Code Online (Sandbox Code Playgroud)
其中dict定义为:
Dictionary<string, CompositeType> dict = new Dictionary<string, CompositeType>();
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" });
Run Code Online (Sandbox Code Playgroud)
但我不想从 WCF 方法返回字符串。这是因为它隐藏了返回的真实类型;而且由于 WCF 也会序列化字符串,导致转义双引号和其他丑陋的内容,使非 .Net REST 客户端更难解析。
这是响应 @dbc 评论的部分解决方案。它产生了这个正确形状的 JSON 结构...
{"fred":{"HasPaid":false,"Owner":"Fred Millhouse"},"joe":{"HasPaid":false,"Owner":"Joe McWirter"},"bob":{"HasPaid":true,"Owner":"Bob Smith"}}
Run Code Online (Sandbox Code Playgroud)
但不幸的是必须将方法的返回类型更改为Message. 界面变成:
[ServiceContract]
public interface IService1
{
[OperationContract]
Message GetDict();
}
Run Code Online (Sandbox Code Playgroud)
并且实现变为:
using Newtonsoft.Json;
using System.ServiceModel.Channels;
...
[WebGet(ResponseFormat = WebMessageFormat.Json)]
public Message GetDict()
{
Dictionary<string, CompositeType> dict = new Dictionary<string, CompositeType>();
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);
}
Run Code Online (Sandbox Code Playgroud)
需要注意的一项有用功能是,与返回时不同Stream,当您访问 REST 方法的 URI 时,您可以在 Web 浏览器中轻松查看 JSON。
| 归档时间: |
|
| 查看次数: |
1131 次 |
| 最近记录: |