2014-01-15 52 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);