How to return a Dictionary of custom type values as a regular JSON object from a WCF REST method?

前端 未结 1 2018
走了就别回头了
走了就别回头了 2020-12-21 04:12

Let\'s say I\'ve got a custom type that looks like this:

[DataContract]
public class CompositeType
{
    [DataMember]
    public bool HasPaid
    {
        g         


        
相关标签:
1条回答
  • 2020-12-21 04:51

    This is a partial solution in response to comments by @dbc. It results in the right-shaped JSON structure of this...

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

    but unfortunately involves having to change the return type of the method to Message. The interface becomes:

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

    and the implementation becomes:

    using Newtonsoft.Json;
    ...
    [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);
    }
    

    One useful feature to note is that, unlike when returning Stream, you can view the JSON easily in your web browser when you visit the REST method's URI.

    0 讨论(0)
提交回复
热议问题