目录

介绍

JSON示例

MVC

Web API

添加设置

枚举

引用循环

引用$ id / $ ref

TimeZone和DateTime


配置JSON序列化设置

介绍

ASP.NET MVC项目中生成JSON时,我发现生成的JSON响应实际上不是驼峰格式。还有:

  • JSON没有缩进
  • 序列化单个null值时出现异常
  • 引用循环属性的异常

今天,我将分享如何使用Newtonsoft.Json并在不同类型的项目中配置JSON序列化设置。

JSON示例

https://www.codeproject.com/KB/aspnet/1276364/Regular.png

https://www.codeproject.com/KB/aspnet/1276364/Expected.png

MVC

使用驼峰格式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
        };
    }
}

添加一个新方法到ControllerBaseController 以使用此帮助类:

/*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())

这也适用于AspxRazorC!!!

如果我们不想在全局范围内配置它,我们可以这样做:

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);

Web API

将新配置类添加到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<JsonConverter> { new StringEnumConverter() }

引用循环

ReferenceLoopHandling = ReferenceLoopHandling.Serialize

引用$ id / $ ref

/*PreserveReferencesHandling.Objects is more popular*/
PreserveReferencesHandling = PreserveReferencesHandling.All;

js客户端要管理$id$ref,请检查:

TimeZoneDateTime

DateTimeZoneHandling = DateTimeZoneHandling.Utc,
DateFormatHandling = DateFormatHandling.IsoDateFormat

本文将帮助您快速启动项目,将JSON序列化程序设置最小化。请检查附带的VS2017示例项目。

 

原文地址:https://www.codeproject.com/Tips/1276364/camelCase-JSON-response-in-ASP-NET-projects

Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐