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的ActionResults返回camelclosure(与标准的PascalCase相反)的JSON数据。NET MVC控制器方法,由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?
我该怎么做呢?
7 个解决方案
#1
247
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
};
#2
84
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)};
}
#3
48
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-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();
#4
28
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();
});
#5
7
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");
#6
7
In ASP.NET Core MVC.
在ASP。网络核心MVC。
public IActionResult Foo()
{
var data = GetData();
var settings = new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
});
return Json(data, settings);
}
#7
6
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实例。这就是发生驼背的原因。
#1
247
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
};
#2
84
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)};
}
#3
48
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-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();
#4
28
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();
});
#5
7
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");
#6
7
In ASP.NET Core MVC.
在ASP。网络核心MVC。
public IActionResult Foo()
{
var data = GetData();
var settings = new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
});
return Json(data, settings);
}
#7
6
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实例。这就是发生驼背的原因。