akn*_*ds1 229 asp.net-mvc json camelcasing json.net
我的问题是我希望通过来自ASP.NET MVC控制器方法的ActionResult返回camelCased(而不是标准的PascalCase)JSON数据,由JSON.NET序列化.
举个例子来考虑以下C#类:
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
默认情况下,当从MVC控制器返回此类的实例作为JSON时,它将按以下方式序列化:
{
"FirstName": "Joe",
"LastName": "Public"
}
Run Code Online (Sandbox Code Playgroud)
我希望它被序列化(通过JSON.NET):
{
"firstName": "Joe",
"lastName": "Public"
}
Run Code Online (Sandbox Code Playgroud)
我该怎么做呢?
Web*_*ver 363
或者,简单地说:
JsonConvert.SerializeObject(
<YOUR OBJECT>,
new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
});
Run Code Online (Sandbox Code Playgroud)
例如:
return new ContentResult
{
ContentType = "application/json",
Content = JsonConvert.SerializeObject(new { content = result, rows = dto }, new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() }),
ContentEncoding = Encoding.UTF8
};
Run Code Online (Sandbox Code Playgroud)
akn*_*ds1 90
我在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));
}
}
Run Code Online (Sandbox Code Playgroud)
然后在MVC控制器方法中使用以下类:
public ActionResult GetPerson()
{
return new JsonCamelCaseResult(new Person { FirstName = "Joe", LastName = "Public" }, JsonRequestBehavior.AllowGet)};
}
Run Code Online (Sandbox Code Playgroud)
Ass*_* S. 57
对于WebAPI,请查看以下链接:http: //odetocode.com/blogs/scott/archive/2013/03/25/asp-net-webapi-tip-3-camelcasing-json.aspx
基本上,将此代码添加到您的Application_Start
:
var formatters = GlobalConfiguration.Configuration.Formatters;
var jsonFormatter = formatters.JsonFormatter;
var settings = jsonFormatter.SerializerSettings;
settings.ContractResolver = new CamelCasePropertyNamesContractResolver();
Run Code Online (Sandbox Code Playgroud)
Qua*_*ium 33
我认为这是您正在寻找的简单答案.这是来自Shawn Wildermuth的博客:
// Add MVC services to the services container.
services.AddMvc()
.AddJsonOptions(opts =>
{
opts.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
});
Run Code Online (Sandbox Code Playgroud)
Stu*_*ows 12
自定义过滤器的替代方法是创建一个扩展方法,将任何对象序列化为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);
}
}
Run Code Online (Sandbox Code Playgroud)
然后从控制器操作返回时调用它.
return Content(person.ToJson(), "application/json");
Run Code Online (Sandbox Code Playgroud)
您必须在文件“Startup.cs”中设置设置
你还必须在 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()
};
}
Run Code Online (Sandbox Code Playgroud)
在ASP.NET Core MVC中.
public IActionResult Foo()
{
var data = GetData();
var settings = new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
});
return Json(data, settings);
}
Run Code Online (Sandbox Code Playgroud)
IMO越简单越好!
你为什么不这样做呢?
public class CourseController : JsonController
{
public ActionResult ManageCoursesModel()
{
return JsonContent(<somedata>);
}
}
Run Code Online (Sandbox Code Playgroud)
简单的基类控制器
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
};
}
}
Run Code Online (Sandbox Code Playgroud)
下面是一个action方法,它通过序列化一个对象数组返回一个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);
}
Run Code Online (Sandbox Code Playgroud)
请注意,JsonSerializerSettings实例作为第二个参数传递.这就是使camelCase发生的原因.
小智 6
Add Json NamingStrategy property to your class definition.
[JsonObject(NamingStrategyType = typeof(CamelCaseNamingStrategy))]
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
我是这样的:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
这是 MVC 核心中的一个简单扩展方法,它将为项目中的每个对象提供 ToJson() 能力,在我看来,在 MVC 项目中,大多数对象都应该具有成为 json 的能力,当然这取决于:)
归档时间: |
|
查看次数: |
117812 次 |
最近记录: |