c# - JSON.NET MVC 4 WebApi

标签 c# json asp.net-mvc-4 json.net

我正在创建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);


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

最佳答案

WebApi已经在管道中使用了Json序列化程序http://www.asp.net/web-api/overview/formats-and-model-binding/json-and-xml-serialization,因此我认为在您显式进行序列化的方法中,结果最终被序列化了两次。第二种方法是您想要的,除非您也删除了json格式器。

关于c# - JSON.NET MVC 4 WebApi,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17452137/

相关文章:

json - Spring 3.0 异常在 POST 上将 String 转换为 java.util.Date

android - 不仅仅是标记自定义信息窗口中的标题和 fragment

c# - 从 MVC 4 Web Api 返回匿名类型失败并出现序列化错误

c# - T 泛型不适用于构建器模式

c# - 如何从具有索引的字典对象中获取特定项目?

c# - 使用 C# 和 LINQ 如何找到重复的文件名?

javascript - 将数组从 javascript 传递到 Controller MVC 4

c# - "throw new NotImplementedException();"到底做了什么?

php - 在php页面上循环访问数据库中的json数据

c# - ASP.NET MVC 4 中的全局变量