簡體   English   中英

如何從WCF REST方法返回自定義類型值的Dictionary作為常規JSON對象?

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

假設我有一個看起來像這樣的自定義類型:

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

    [DataMember]
    public string Owner
    {
        get;
        set;
    }
}

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

[ServiceContract]
public interface IService1
{
    [OperationContract]
    Dictionary<string, CompositeType> 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<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" });

但我不想從我的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<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);
}

需要注意的一個有用功能是,與返回Stream時不同,當您訪問REST方法的URI時, 可以在Web瀏覽器中輕松查看JSON。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM