目录
介绍
JSON示例
MVC
Web API
添加设置
枚举
引用循环
引用$ id / $ ref
TimeZone和DateTime
配置JSON序列化设置
在ASP.NET MVC项目中生成JSON时,我发现生成的JSON响应实际上不是驼峰格式。还有:
今天,我将分享如何使用Newtonsoft.Json并在不同类型的项目中配置JSON序列化设置。
使用驼峰格式JSON 的自定义JsonResult类:
using System;
using System.Text;
using System.Web;
using System.Web.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
public class JsonCamelCaseResult : JsonResult
{
public Encoding ContentEncoding { get; set; }
public string ContentType { get; set; }
public object Data { get; set; }
private const string HttpMethod = "GET";
private const string DefaultContentType = "application/json";
public override void ExecuteResult(ControllerContext context)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
if (JsonRequestBehavior == JsonRequestBehavior.DenyGet &&
String.Equals(context.HttpContext.Request.HttpMethod,
HttpMethod, StringComparison.OrdinalIgnoreCase))
{
throw new InvalidOperationException("HttpMethod 'GET' is not allowed");
}
HttpResponseBase response = context.HttpContext.Response;
response.ContentType = string.IsNullOrEmpty(ContentType) ? DefaultContentType : ContentType;
if (ContentEncoding != null)
{
response.ContentEncoding = ContentEncoding;
}
var jsonSerializerSettings = new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver(),
Formatting = Formatting.Indented,
ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
PreserveReferencesHandling = PreserveReferencesHandling.None /*prevent $id/$ref
at client end*/
};
response.Write(JsonConvert.SerializeObject(Data, jsonSerializerSettings));
}
}
JSON帮助类:
public class CamelJsonHelper
{
public JsonCamelCaseResult Json(object data)
{
return new JsonCamelCaseResult
{
Data = data,
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
}
添加一个新方法到Controller或BaseController 以使用此帮助类:
/*hide base*/
//public new JsonResult Json(object value)
//{
// return new CamelJsonHelper().Json(value);
//}
/*new method*/
public JsonResult JsonCamel(object value)
{
return new CamelJsonHelper().Json(value);
}
对于MVC项目,没有全局设置选项。
Web表单
在Global.asax.cs中添加序列化设置。
/*comment and see the regular serialization*/
JsonConvert.DefaultSettings = () => new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver(),
Formatting = Formatting.Indented,
ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
PreserveReferencesHandling = PreserveReferencesHandling.None /*prevent $id/$ref at client end*/
};
现在序列化对象,如下:
string json = JsonConvert.SerializeObject(DataProvider.Hierarchy())
这也适用于Aspx,Razor和C#!!!
如果我们不想在全局范围内配置它,我们可以这样做:
var settings = new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver(),
Formatting = Formatting.Indented,
ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
PreserveReferencesHandling = PreserveReferencesHandling.None /*prevent $id/$ref at client end*/
};
var data = DataProvider.Hierarchy();
string json = JsonConvert.SerializeObject(data, settings);
将新配置类添加到App_Start:
public class ResponseSerializerConfig
{
public static void Register(HttpConfiguration configuration)
{
JsonResponse(configuration);
XmlResponse(configuration);
}
private static void XmlResponse(HttpConfiguration config)
{
config.Formatters.Remove(config.Formatters.XmlFormatter);
}
private static void JsonResponse(HttpConfiguration config)
{
config.Formatters.JsonFormatter.SerializerSettings = new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver(),
Formatting = Formatting.Indented,
ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
PreserveReferencesHandling = PreserveReferencesHandling.None /*prevent $id/$ref
at client end*/
};
}
}
在Global.asax.cs中应用此配置类。
ResponseSerializerConfig.Register(GlobalConfiguration.Configuration);
{"Enum":"Hello"} 而不是 {"Enum":0}
Converters = new List { new StringEnumConverter() }
ReferenceLoopHandling = ReferenceLoopHandling.Serialize
/*PreserveReferencesHandling.Objects is more popular*/
PreserveReferencesHandling = PreserveReferencesHandling.All;
在js客户端要管理$id/ $ref,请检查:
DateTimeZoneHandling = DateTimeZoneHandling.Utc,
DateFormatHandling = DateFormatHandling.IsoDateFormat
本文将帮助您快速启动项目,将JSON序列化程序设置最小化。请检查附带的VS2017示例项目。
原文地址:https://www.codeproject.com/Tips/1276364/camelCase-JSON-response-in-ASP-NET-projects