我正在创建控制器以返回 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);
我对正在发生的事情感到困惑。