鉴于以下类(class),

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

    public string Message { get; set; }
}

我将在这样的Controller Action 中返回其中之一,
return Json(new Result() { Success = true, Message = "test"})

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

最佳答案

实现此目的的方法是实现一个自定义的JsonResult,如下所示:
Creating a custom ValueType and Serialising with a custom 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"
  ]
}

10-04 23:09
查看更多