gpt4 book ai didi

asp.net-mvc - 从 ASP.NET MVC 中的 Json() 强制小写属性名称

转载 作者:IT老高 更新时间:2023-10-28 12:43:00 26 4
gpt4 key购买 nike

鉴于以下类(class),

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

public string Message { get; set; }
}

我正在像这样的 Controller 操作中返回其中一个,

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"
]
}

关于asp.net-mvc - 从 ASP.NET MVC 中的 Json() 强制小写属性名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2789593/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com