1

我正在创建控制器以返回 JSON 格式的对象。我想使用 Newtonsoft.Json 库。我创建了两种方法:

[HttpGet]
[ActionName("RetrieveTestClassJson")]
public ActionResult RetrieveTestClassJson(int id)
{
    TestThing testThing = new TestThing() { Name = "LPL.22.334", Type = TypeTest.Component };
    JsonNetResult jsonNetResult = new JsonNetResult();
    jsonNetResult.Formatting = Formatting.Indented;
    jsonNetResult.ContentType = "application/json";
    jsonNetResult.ContentEncoding = Encoding.Unicode;
    jsonNetResult.Data = testThing;
    return jsonNetResult;
}

[HttpGet]
[ActionName("RetrieveTestClassCase2")]
public TestThing RetrieveTestClassCase2(int id)
{
    TestThing testThing = new TestThing() { Name = "LPL.22.334", Type = TypeTest.Component };
    return testThing;
}

当我从 ajax 或浏览器 url 调用 RetrieveTestClassJson 时,我得到:

{"ContentEncoding":{"isThrowException":false,"bigEndian":false,"byteOrderMark":true,"m_codePage":1200,"dataItem":null,"encoderFallback":{"strDefault":"�","bIsMicrosoftBestFitFallback":false},"decoderFallback":{"strDefault":"�","bIsMicrosoftBestFitFallback":false},"m_isReadOnly":true},"ContentType":"application/json","Data":{"Name":"LPL.22.334"},"SerializerSettings":{"ReferenceLoopHandling":0,"MissingMemberHandling":0,"ObjectCreationHandling":0,"NullValueHandling":0,"DefaultValueHandling":0,"Converters":[{"CamelCaseText":true,"CanRead":true,"CanWrite":true}],"PreserveReferencesHandling":0,"TypeNameHandling":0,"TypeNameAssemblyFormat":0,"ConstructorHandling":0,"ContractResolver":null,"ReferenceResolver":null,"TraceWriter":null,"Binder":null,"Error":null,"Context":{"m_additionalContext":null,"m_state":0},"DateFormatString":"yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK","MaxDepth":null,"Formatting":0,"DateFormatHandling":0,"DateTimeZoneHandling":3,"DateParseHandling":1,"FloatFormatHandling":0,"FloatParseHandling":0,"StringEscapeHandling":0,"Culture":"(Default)","CheckAdditionalContent":false},"Formatting":1}

当我调用 RetrieveTestClassCase2 时,我得到了正常的 JSON 格式。我现在出于测试目的删除了 xml 处理程序:

var appXmlType = config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml");
config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType);

我对正在发生的事情感到困惑。

4

2 回答 2

6

WebApi 已经在管道中拥有 Json 序列化程序,http://www.asp.net/web-api/overview/formats-and-model-binding/json-and-xml-serialization,所以我认为在你的方法中你是显式序列化的,结果会被序列化两次。第二种方法是您想要的,除非您也删除了 json 格式化程序。

于 2013-07-03T15:42:33.127 回答
4

当你什么都不做时它返回 JSON 的原因是 MVC 在 JSON 序列化器中有自己的构建。由于这是一个

[System.Web.Http.HttpGet]

不是

[System.Web.Mvc.HttpGet]

它将您发送的内容视为数据而不是标记。这就是为什么它将您的对象作为 JSON 返回的原因。它知道您发送的只是一个对象,因此它会为您序列化它。如果您想要 [System.Web.Mvc.HttpGet] 中的相同功能,您将返回 JsonResult 而不是 ActionResult。

var result = new JsonResult();
result.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
result.Data = testThing;
于 2013-07-03T15:46:00.417 回答