返回带有小写首字母属性名称的json

时间:2016-04-27 08:09:39

标签: c# json asp.net-web-api

我有LoginModel:

public class LoginModel : IData
{
    public string Email { get; set; }
    public string Password { get; set; }
}

我有Web api方法

public IHttpActionResult Login([FromBody] LoginModel model)
{
    return this.Ok(model);
}

它返回200和身体:

{
    Email: "dfdf",
    Password: "dsfsdf"
}

但我希望在

等属性中获得较低的首字母
{
    email: "dfdf",
    password: "dsfsdf"
}

我有Json合同解析器用于纠正

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)}";
    }
}

我如何申请?

4 个答案:

答案 0 :(得分:17)

要强制从api返回的所有json数据到驼峰,使用默认的驼峰式合约解析器更容易使用Newtonsoft Json。

创建一个类似这样的类:

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配置期间(启动时)设置:

var jsonFormatter = new JsonMediaTypeFormatter();
httpConfiguration.Services.Replace(typeof(IContentNegotiator), new JsonContentNegotiator(jsonFormatter));

答案 1 :(得分:16)

如果您使用 Newtonsoft.Json ,则可以将 JsonProperties 添加到视图模型中:

public class LoginModel : IData
{
     [JsonProperty(PropertyName = "email")]
     public string Email {get;set;}

     [JsonProperty(PropertyName = "password")]
     public string Password {get;set;}
}

答案 2 :(得分:2)

您可以在Web API配置或启动文件

中添加以下两个语句
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;

GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.Formatting = Formatting.Indented;

非常重要使用await方法代替return Ok() ,否则这将无效。

答案 3 :(得分:0)

如果仅在某个特定位置而不是整个应用程序中都需要它,则可以执行以下操作:

var objectToSerialize = new {Property1 = "value1", SubOjbect = new { SubObjectId = 1 }};
var json = Newtonsoft.Json.JsonConvert.SerializeObject(data, new JsonSerializerSettings { ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver() });

它应产生{"property1":"value1","subOjbect":{"subObjectId":1}}(请注意,嵌套属性也从小写字母开始)