285

我的问题是我希望通过来自 ASP.NET MVC 控制器方法的ActionResult返回 camelCased(而不是标准 PascalCase)JSON 数据,并由JSON.NET序列化。

例如,考虑以下 C# 类:

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

默认情况下,当从 MVC 控制器以 JSON 形式返回此类的实例时,它将以下列方式序列化:

{
  "FirstName": "Joe",
  "LastName": "Public"
}

我希望它被序列化(通过 JSON.NET)为:

{
  "firstName": "Joe",
  "lastName": "Public"
}

我该怎么做呢?

4

13 回答 13

451

或者,简单地说:

JsonConvert.SerializeObject(
    <YOUR OBJECT>, 
    new JsonSerializerSettings 
    { 
        ContractResolver = new CamelCasePropertyNamesContractResolver() 
    });

例如:

return new ContentResult
{
    ContentType = "application/json",
    Content = JsonConvert.SerializeObject(new { content = result, rows = dto }, new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() }),
    ContentEncoding = Encoding.UTF8
};
于 2014-03-18T15:00:20.890 回答
103

我在 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));
    }
}

然后在你的 MVC 控制器方法中使用这个类,如下所示:

public ActionResult GetPerson()
{
    return new JsonCamelCaseResult(new Person { FirstName = "Joe", LastName = "Public" }, JsonRequestBehavior.AllowGet)};
}
于 2013-10-18T09:07:42.963 回答
61

对于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();
于 2015-02-05T06:33:17.203 回答
41

我认为这是您正在寻找的简单答案。来自Shawn Wildermuth的博客:

// Add MVC services to the services container.
services.AddMvc()
  .AddJsonOptions(opts =>
  {
    opts.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
  });
于 2016-01-06T21:30:11.727 回答
13

自定义过滤器的替代方法是创建一个扩展方法来将任何对象序列化为 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);
    }
}

然后在从控制器动作返回时调用它。

return Content(person.ToJson(), "application/json");
于 2016-05-25T07:58:28.483 回答
12

IMO 越简单越好!

你为什么不这样做?

public class CourseController : JsonController
{
    public ActionResult ManageCoursesModel()
    {
        return JsonContent(<somedata>);
    }
}

简单的基类控制器

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
        };
    }
}
于 2019-01-30T05:51:28.840 回答
9

您必须在文件“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()
        };
    }
于 2019-07-30T18:06:28.753 回答
9

将 Json NamingStrategy属性添加到您的类定义中。

[JsonObject(NamingStrategyType = typeof(CamelCaseNamingStrategy))]
public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

于 2020-08-24T11:25:56.123 回答
8

下面是一个动作方法,它通过序列化一个对象数组来返回一个 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);
    }

请注意作为第二个参数传递的 JsonSerializerSettings 实例。这就是骆驼案发生的原因。

于 2014-03-28T05:06:41.743 回答
7

在 ASP.NET Core MVC 中。

    public IActionResult Foo()
    {
        var data = GetData();

        var settings = new JsonSerializerSettings 
        { 
            ContractResolver = new CamelCasePropertyNamesContractResolver() 
        });

        return Json(data, settings);
    }
于 2016-10-05T14:10:01.120 回答
6

我确实喜欢这样:

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

这是 MVC 核心中的一个简单扩展方法,它将为项目中的每个对象赋予 ToJson() 能力,在我看来,在 MVC 项目中,大多数对象应该具有成为 json 的能力,当然这取决于:)

于 2019-01-17T07:16:10.587 回答
0

如果您在 .net core web api 中返回 ActionResult 或 IHttpAction 结果,那么您只需将模型包装在 Ok() 方法中,该方法将匹配您前端的案例并为您序列化它。无需使用 JsonConvert。:)

于 2020-01-31T15:44:13.113 回答
-1

安装包 Microsoft.AspNetCore.Mvc.NewtonsoftJson

这解决了我的问题

于 2021-12-24T22:42:10.527 回答