如何从ASP.NET MVC控制器方法返回JSON.NET序列化的camelCase JSON?

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)

  • 但这使用起来更复杂,因为您必须为每个控制器方法配置ContentResult. (2认同)
  • 是的,我明白你的答案是一个可重用的解决方案,我的观点是要更清楚地说它只是Serialize方法的一个参数. (2认同)

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)

  • 完美的答案:清洁和可重复使用!谢谢. (3认同)
  • 虽然这个解决方案仍然有效。但这是 4 年前提出的。我们有更好的解决方案吗? (2认同)
  • @SharpCoder,三年后的现在,您是否找到了更好的替代方案? (2认同)

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)

  • Web API和MVC已在ASP.NET 6中合并 (4认同)
  • 链接方便;这个设置非常适合这个答案:http://stackoverflow.com/a/26068063/398630(不同的问题,但我一起使用它们,这个链接可能会为我和其他人节省一些未来的谷歌搜索)。 (2认同)

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)

  • 具有讽刺意味的是,我来到这里寻找你在这里回答的问题的答案,所以虽然这不是OP问题的答案,但无论如何它帮助了我.谢谢!:) (8认同)
  • fyi对于ASP.NET Core 1.0,默认为OOTB的驼峰 (4认同)
  • 事实证明,这毕竟不是(确切).NET Core 1.0的默认设置.此解决方案会影响动态属性,默认情况下不受此影响.http://stackoverflow.com/questions/41329279/net-core-json-serialization-of-properties-on-dynamic-expandoobject/41372895#41372895 (3认同)
  • 道歉,伙计们.我读得太快了.它适用于ASP.NET 5. (2认同)

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)


Dan*_*hez 8

您必须在文件“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)


Fre*_*red 7

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


jwi*_*ize 7

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)


Dan*_*odi 6

下面是一个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)


Ali*_*Alp 5

我是这样的:

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 的能力,当然这取决于:)

  • 考虑在方法外部提取“settings”变量(作为私有静态字段“camelCaseSettings”),这样就不会在每次调用 ToJson 方法时都初始化新变量。 (2认同)