在ASP.NET MVC中从Json()强制使用小写属性名称


89

鉴于以下课程,

public class Result
{      
    public bool Success { get; set; }

    public string Message { get; set; }
}

我将像这样在Controller动作中返回其中之一,

return Json(new Result() { Success = true, Message = "test"})

但是我的客户端框架期望这些属性是小写的成功和信息。不必实际上具有小写的属性名称,是否可以通过正常的Json函数调用来实现这一想法?

Answers:


130

实现此目的的方法是实现一个JsonResult类似此处的自定义: 创建自定义ValueType并使用自定义JsonResult进行序列化 (原始链接无效

并使用替代的序列化器,例如JSON.NET,它支持这种行为,例如:

Product product = new Product
{
  ExpiryDate = new DateTime(2010, 12, 20, 18, 1, 0, DateTimeKind.Utc),
  Name = "Widget",
  Price = 9.99m,
  Sizes = new[] {"Small", "Medium", "Large"}
};

string json = 
  JsonConvert.SerializeObject(
    product,
    Formatting.Indented,
    new JsonSerializerSettings 
    { 
      ContractResolver = new CamelCasePropertyNamesContractResolver() 
    }
);

结果是

{
  "name": "Widget",
  "expiryDate": "\/Date(1292868060000)\/",
  "price": 9.99,
  "sizes": [
    "Small",
    "Medium",
    "Large"
  ]
}


如果您使用的是JSON.NET,并且不想使用camelCase而是snake_case,请查看此要点,对我有很大帮助!gist.github.com/crallen/9238178
Niclas Lindqvist

我如何反序列化?例如 从“小”到“小”
菜鸟2016年

1
@NiclasLindqvist对于现代JSON.NET版本,还有以获得snake_case一个更简单的方法:newtonsoft.com/json/help/html/NamingStrategySnakeCase.htm
索伦Boisen

17

如果使用Web API,更改序列化程序很简单,但是不幸的是,MVC本身使用JavaScriptSerializer没有选项将其更改为使用JSON.Net。

James的答案Daniel的答案为您提供了JSON.Net的灵活性,但是这意味着您通常需要在任何地方return Json(obj)进行更改return new JsonNetResult(obj)或类似操作,如果您有大型项目,则可能会遇到问题,并且如果使用大型项目​​,它也不太灵活您对要使用的序列化器改变了主意。


我决定走这ActionFilter条路。以下代码允许您使用进行任何操作,JsonResult并简单地向其应用属性以使用JSON.Net(具有小写属性):

[JsonNetFilter]
[HttpPost]
public ActionResult SomeJson()
{
    return Json(new { Hello = "world" });
}

// outputs: { "hello": "world" }

您甚至可以将其设置为自动应用于所有操作(仅对次要性能造成影响is):

FilterConfig.cs

// ...
filters.Add(new JsonNetFilterAttribute());

编码

public class JsonNetFilterAttribute : ActionFilterAttribute
{
    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        if (filterContext.Result is JsonResult == false)
            return;

        filterContext.Result = new CustomJsonResult((JsonResult)filterContext.Result);
    }

    private class CustomJsonResult : JsonResult
    {
        public CustomJsonResult(JsonResult jsonResult)
        {
            this.ContentEncoding = jsonResult.ContentEncoding;
            this.ContentType = jsonResult.ContentType;
            this.Data = jsonResult.Data;
            this.JsonRequestBehavior = jsonResult.JsonRequestBehavior;
            this.MaxJsonLength = jsonResult.MaxJsonLength;
            this.RecursionLimit = jsonResult.RecursionLimit;
        }

        public override void ExecuteResult(ControllerContext context)
        {
            if (context == null)
                throw new ArgumentNullException("context");

            if (this.JsonRequestBehavior == JsonRequestBehavior.DenyGet
                && String.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
                throw new InvalidOperationException("GET not allowed! Change JsonRequestBehavior to AllowGet.");

            var response = context.HttpContext.Response;

            response.ContentType = String.IsNullOrEmpty(this.ContentType) ? "application/json" : this.ContentType;

            if (this.ContentEncoding != null)
                response.ContentEncoding = this.ContentEncoding;

            if (this.Data != null)
            {
                var json = JsonConvert.SerializeObject(
                    this.Data,
                    new JsonSerializerSettings
                        {
                            ContractResolver = new CamelCasePropertyNamesContractResolver()
                        });

                response.Write(json);
            }
        }
    }
}

10

使用我的解决方案,您可以重命名所需的每个属性。

我已经找到了解决方案的一部分,在这里和SO

public class JsonNetResult : ActionResult
    {
        public Encoding ContentEncoding { get; set; }
        public string ContentType { get; set; }
        public object Data { get; set; }

        public JsonSerializerSettings SerializerSettings { get; set; }
        public Formatting Formatting { get; set; }

        public JsonNetResult(object data, Formatting formatting)
            : this(data)
        {
            Formatting = formatting;
        }

        public JsonNetResult(object data):this()
        {
            Data = data;
        }

        public JsonNetResult()
        {
            Formatting = Formatting.None;
            SerializerSettings = new JsonSerializerSettings();
        }

        public override void ExecuteResult(ControllerContext context)
        {
            if (context == null)
                throw new ArgumentNullException("context");
            var response = context.HttpContext.Response;
            response.ContentType = !string.IsNullOrEmpty(ContentType)
              ? ContentType
              : "application/json";
            if (ContentEncoding != null)
                response.ContentEncoding = ContentEncoding;

            if (Data == null) return;

            var writer = new JsonTextWriter(response.Output) { Formatting = Formatting };
            var serializer = JsonSerializer.Create(SerializerSettings);
            serializer.Serialize(writer, Data);
            writer.Flush();
        }
    }

这样我可以在控制器中做到这一点

        return new JsonNetResult(result);

在我的模型中,我现在可以拥有:

    [JsonProperty(PropertyName = "n")]
    public string Name { get; set; }

请注意,现在,您必须将设置为JsonPropertyAttribute要序列化的每个属性。


1

尽管这是一个古老的问题,但希望以下代码段对其他人有所帮助,

我在下面使用了MVC5 Web API。

public JsonResult<Response> Post(Request request)
    {
        var response = new Response();

        //YOUR LOGIC IN THE METHOD
        //.......
        //.......

        return Json<Response>(response, new JsonSerializerSettings() { ContractResolver = new CamelCasePropertyNamesContractResolver() });
    }

0

您可以将此设置添加到Global.asax,并且可以在任何地方使用。

public class Global : HttpApplication
{   
    void Application_Start(object sender, EventArgs e)
    {
        //....
         JsonConvert.DefaultSettings = () =>
         {
             var settings = new JsonSerializerSettings
             {
                 ContractResolver = new CamelCasePropertyNamesContractResolver(),
                 PreserveReferencesHandling = PreserveReferencesHandling.None,
                 Formatting = Formatting.None
             };

             return settings;
         }; 
         //....
     }
}
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.