2014-01-15 54 views
0

我打電話給我使用MVC4 ApiController編寫的Web API。

它返回一個Dictionary<int, int>這樣的:

return Request.CreateResponse<Dictionary<int, int>>(HttpStatusCode.OK, histogram); 

這將返回以下JSON對象:

{ 
    "$type": "System.Collections.Generic.Dictionary`2[[System.Int32, mscorlib],[System.Int32, mscorlib]], mscorlib", 
    "4": 113, 
    "0": 716, 
    "1": 443, 
    "2": 226, 
    "3": 123, 
    "5": 4, 
    "26": 3 
} 

該對象具有屬性$type引用它對應於.NET類型。我不希望這個被髮送給我的客戶。

我該如何擺脫$type屬性?

+0

http://stackoverflow.com/questions/1636885/remove-item-到jsson前in-dictionary-based-value- –

+0

不要返回字典,它只針對.NET,對於任何不是.NET客戶端的api消費者都是毫無意義的。 – Maess

+0

我的API調用只是將一些鍵/值對作爲JSON對象返回。我知道一個字典是特定於.NET的;這恰好是我的控制器中鍵/值對的表現方式。 '$ type'屬性不在我要返回的字典中。 MVC似乎是自己添加屬性。 – jcarpenter2

回答

1

我知道發生了什麼事。基本上,我自己做到了。

我需要做出改變,以我的WebApiConfig.cs文件:

public static void Register(HttpConfiguration config) 
{ 
    // ... 

    // remove this line: 
    config.Formatters.JsonFormatter.SerializerSettings.TypeNameHandling = Newtonsoft.Json.TypeNameHandling.Objects; 
} 

我刪除了這條線後,$type物業停止顯示我的API控制方法的結果了。

這引出了一個問題:是否有可能使用$type屬性來實例化時來電到Web API正確的類,而留下$type地產出傳出JSON或XML的?

1

不返回字典,因爲它已經提到您更好地轉換的 直方圖後端

string json = JsonConvert.SerializeObject(histogram, Formatting.Indented, new JsonSerializerSettings 
     { 
     TypeNameHandling = TypeNameHandling.All, 
     TypeNameAssemblyFormat = FormatterAssemblyStyle.Simple 
     }); 

return Request.CreateResponse(HttpStatusCode.OK, json);