如何从 ASP.NET MVC 控制器方法返回由 JSON.NET 序列化的camelCase JSON?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19445730/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I return camelCase JSON serialized by JSON.NET from ASP.NET MVC controller methods?
提问by aknuds1
My problem is that I wish to return camelCased (as opposed to the standard PascalCase) JSON data via ActionResults from ASP.NET MVC controller methods, serialized by JSON.NET.
我的问题是我希望通过ASP.NET MVC 控制器方法中的ActionResult返回camelCased(而不是标准PascalCase)JSON数据,由JSON.NET序列化。
As an example consider the following C# class:
例如,考虑以下 C# 类:
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
By default, when returning an instance of this class from an MVC controller as JSON, it'll be serialized in the following fashion:
默认情况下,当从 MVC 控制器返回此类的实例作为 JSON 时,它将以以下方式序列化:
{
"FirstName": "Joe",
"LastName": "Public"
}
I would like it to be serialized (by JSON.NET) as:
我希望它被序列化(通过 JSON.NET)为:
{
"firstName": "Joe",
"lastName": "Public"
}
How do I do this?
我该怎么做呢?
采纳答案by aknuds1
I found an excellent solution to this problem on Mats Karlsson's blog. The solution is to write a subclass of ActionResult that serializes data via JSON.NET, configuring the latter to follow the camelCase convention:
我在 Mats Karlsson 的博客上找到了一个很好的解决方案。解决方案是编写一个ActionResult的子类,通过JSON.NET序列化数据,配置后者遵循camelCase约定:
public class JsonCamelCaseResult : ActionResult
{
public JsonCamelCaseResult(object data, JsonRequestBehavior jsonRequestBehavior)
{
Data = data;
JsonRequestBehavior = jsonRequestBehavior;
}
public Encoding ContentEncoding { get; set; }
public string ContentType { get; set; }
public object Data { get; set; }
public JsonRequestBehavior JsonRequestBehavior { get; set; }
public override void ExecuteResult(ControllerContext context)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
if (JsonRequestBehavior == JsonRequestBehavior.DenyGet && String.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
{
throw new InvalidOperationException("This request has been blocked because sensitive information could be disclosed to third party web sites when this is used in a GET request. To allow GET requests, set JsonRequestBehavior to AllowGet.");
}
var response = context.HttpContext.Response;
response.ContentType = !String.IsNullOrEmpty(ContentType) ? ContentType : "application/json";
if (ContentEncoding != null)
{
response.ContentEncoding = ContentEncoding;
}
if (Data == null)
return;
var jsonSerializerSettings = new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
};
response.Write(JsonConvert.SerializeObject(Data, jsonSerializerSettings));
}
}
Then use this class as follows in your MVC controller method:
然后在您的 MVC 控制器方法中按如下方式使用此类:
public ActionResult GetPerson()
{
return new JsonCamelCaseResult(new Person { FirstName = "Joe", LastName = "Public" }, JsonRequestBehavior.AllowGet)};
}
回答by WebDever
or, simply put:
或者,简单地说:
JsonConvert.SerializeObject(
<YOUR OBJECT>,
new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
});
For instance:
例如:
return new ContentResult
{
ContentType = "application/json",
Content = JsonConvert.SerializeObject(new { content = result, rows = dto }, new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() }),
ContentEncoding = Encoding.UTF8
};
回答by Assaf S.
For WebAPI, check out this link: http://odetocode.com/blogs/scott/archive/2013/03/25/asp-net-webapi-tip-3-camelcasing-json.aspx
对于WebAPI,请查看此链接:http: //odetocode.com/blogs/scott/archive/2013/03/25/asp-net-webapi-tip-3-camelcasing-json.aspx
Basically, add this code to your Application_Start:
基本上,将此代码添加到您的Application_Start:
var formatters = GlobalConfiguration.Configuration.Formatters;
var jsonFormatter = formatters.JsonFormatter;
var settings = jsonFormatter.SerializerSettings;
settings.ContractResolver = new CamelCasePropertyNamesContractResolver();
回答by Quantium
I think this is the simple answer you are looking for. It's from Shawn Wildermuth's blog:
我认为这是您正在寻找的简单答案。它来自Shawn Wildermuth的博客:
// Add MVC services to the services container.
services.AddMvc()
.AddJsonOptions(opts =>
{
opts.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
});
回答by Stuart Hallows
An alternative to the custom filter is to create an extension method to serialize any object to JSON.
自定义过滤器的替代方法是创建一个扩展方法来将任何对象序列化为 JSON。
public static class ObjectExtensions
{
/// <summary>Serializes the object to a JSON string.</summary>
/// <returns>A JSON string representation of the object.</returns>
public static string ToJson(this object value)
{
var settings = new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver(),
Converters = new List<JsonConverter> { new StringEnumConverter() }
};
return JsonConvert.SerializeObject(value, settings);
}
}
Then call it when returning from the controller action.
然后在从控制器动作返回时调用它。
return Content(person.ToJson(), "application/json");
回答by jwize
Simpler is better IMO!
IMO 越简单越好!
Why don't you do this?
你为什么不这样做?
public class CourseController : JsonController
{
public ActionResult ManageCoursesModel()
{
return JsonContent(<somedata>);
}
}
The simple base class controller
简单的基类控制器
public class JsonController : BaseController
{
protected ContentResult JsonContent(Object data)
{
return new ContentResult
{
ContentType = "application/json",
Content = JsonConvert.SerializeObject(data, new JsonSerializerSettings {
ContractResolver = new CamelCasePropertyNamesContractResolver() }),
ContentEncoding = Encoding.UTF8
};
}
}
回答by Fred
In ASP.NET Core MVC.
在 ASP.NET Core MVC 中。
public IActionResult Foo()
{
var data = GetData();
var settings = new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
});
return Json(data, settings);
}
回答by DanKodi
Below is an action method that returns a json string (cameCase) by serializing an array of objects.
下面是一个动作方法,它通过序列化一个对象数组来返回一个 json 字符串(cameCase)。
public string GetSerializedCourseVms()
{
var courses = new[]
{
new CourseVm{Number = "CREA101", Name = "Care of Magical Creatures", Instructor ="Rubeus Hagrid"},
new CourseVm{Number = "DARK502", Name = "Defence against dark arts", Instructor ="Severus Snape"},
new CourseVm{Number = "TRAN201", Name = "Transfiguration", Instructor ="Minerva McGonal"}
};
var camelCaseFormatter = new JsonSerializerSettings();
camelCaseFormatter.ContractResolver = new CamelCasePropertyNamesContractResolver();
return JsonConvert.SerializeObject(courses, camelCaseFormatter);
}
Note the JsonSerializerSettings instance passed as the second parameter. That's what makes the camelCase happen.
请注意作为第二个参数传递的 JsonSerializerSettings 实例。这就是使camelCase发生的原因。
回答by Ali Alp
I did like this :
我是这样的:
public static class JsonExtension
{
public static string ToJson(this object value)
{
var settings = new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver(),
NullValueHandling = NullValueHandling.Ignore,
ReferenceLoopHandling = ReferenceLoopHandling.Serialize
};
return JsonConvert.SerializeObject(value, settings);
}
}
this a simple extension method in MVC core , it's going to give the ToJson() ability to every object in your project , In my opinion in a MVC project most of object should have the ability to become json ,off course it depends :)
这是 MVC 核心中的一个简单扩展方法,它将为项目中的每个对象提供 ToJson() 能力,在我看来,在 MVC 项目中,大多数对象都应该具有成为 json 的能力,当然这取决于:)
回答by Daniel Sánchez
You must set the settings in the file 'Startup.cs'
您必须在文件“Startup.cs”中进行设置
You also have to define it in the default values of JsonConvert, this is if you later want to directly use the library to serialize an object.
您还必须在 JsonConvert 的默认值中定义它,如果您以后想直接使用该库来序列化对象。
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
.AddJsonOptions(options => {
options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
});
JsonConvert.DefaultSettings = () => new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore,
ContractResolver = new CamelCasePropertyNamesContractResolver()
};
}

