返回带有属性名称小写首字母的json [英] Return json with lower case first letter of property names
本文介绍了返回带有属性名称小写首字母的json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有LoginModel:
I have LoginModel:
public class LoginModel : IData
{
public string Email { get; set; }
public string Password { get; set; }
}
并且我有Web api方法
and I have the Web api method
public IHttpActionResult Login([FromBody] LoginModel model)
{
return this.Ok(model);
}
返回200和正文:
{
Email: "dfdf",
Password: "dsfsdf"
}
但是我想在属性中使用较低的首字母
But I want to get with lower first letter in property like
{
email: "dfdf",
password: "dsfsdf"
}
我有Json合同解析器可以更正
And I have Json contract resolver for correcting
public class FirstLowerContractResolver : DefaultContractResolver
{
protected override string ResolvePropertyName(string propertyName)
{
if (string.IsNullOrWhiteSpace(propertyName))
return string.Empty;
return $"{char.ToLower(propertyName[0])}{propertyName.Substring(1)}";
}
}
该如何应用?
推荐答案
要将从api返回的所有json数据强制转换为驼峰式案例,更容易将Newtonsoft Json与默认的驼峰式案例合同解析器一起使用.
To force all json data returned from api to camel case it's easier to use Newtonsoft Json with the default camel case contract resolver.
创建一个像这样的类:
using Newtonsoft.Json.Serialization;
internal class JsonContentNegotiator : IContentNegotiator
{
private readonly JsonMediaTypeFormatter _jsonFormatter;
public JsonContentNegotiator(JsonMediaTypeFormatter formatter)
{
_jsonFormatter = formatter;
_jsonFormatter.SerializerSettings.ContractResolver =
new CamelCasePropertyNamesContractResolver();
}
public ContentNegotiationResult Negotiate(Type type, HttpRequestMessage request, IEnumerable<MediaTypeFormatter> formatters)
{
return new ContentNegotiationResult(_jsonFormatter, new MediaTypeHeaderValue("application/json"));
}
}
并在api配置(启动时)中进行设置:
and set this during api configuration (at startup):
var jsonFormatter = new JsonMediaTypeFormatter();
httpConfiguration.Services.Replace(typeof(IContentNegotiator), new JsonContentNegotiator(jsonFormatter));
这篇关于返回带有属性名称小写首字母的json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文