我正在创建Controller以返回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);
我对正在发生的事情感到困惑。
答案 0 :(得分:6)
WebApi已经在管道中使用了Json序列化程序http://www.asp.net/web-api/overview/formats-and-model-binding/json-and-xml-serialization,因此我认为在您明确序列化的方法中,结果最终会序列化两次。第二种方法是你想要的,除非你也删除了json格式化程序。
答案 1 :(得分: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;