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

Mih*_*lPw 20 c# json asp.net-web-api

我有LoginModel:

public class LoginModel : IData
{
    public string Email { get; set; }
    public string Password { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我有Web api方法

public IHttpActionResult Login([FromBody] LoginModel model)
{
    return this.Ok(model);
}
Run Code Online (Sandbox Code Playgroud)

它返回200和身体:

{
    Email: "dfdf",
    Password: "dsfsdf"
}
Run Code Online (Sandbox Code Playgroud)

但是我希望能够获得较低的首字母属性

{
    email: "dfdf",
    password: "dsfsdf"
}
Run Code Online (Sandbox Code Playgroud)

我有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)}";
    }
}
Run Code Online (Sandbox Code Playgroud)

我怎么能申请这个?

Luc*_*rsi 19

为了强制从api返回的所有json数据到camel case,使用默认的camel case合约解析器更容易使用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"));
    }
}
Run Code Online (Sandbox Code Playgroud)

并在api配置期间(启动时)设置此项:

var jsonFormatter = new JsonMediaTypeFormatter();
httpConfiguration.Services.Replace(typeof(IContentNegotiator), new JsonContentNegotiator(jsonFormatter));
Run Code Online (Sandbox Code Playgroud)


Adr*_*ris 19

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

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

     [JsonProperty(PropertyName = "password")]
     public string Password {get;set;}
}
Run Code Online (Sandbox Code Playgroud)


Hak*_*tık 10

可以在web API的配置或者启动文件中添加如下两条语句

使用 Newtonsoft.Json;
使用 Newtonsoft.Json.Serialization;

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

但是使用方法而不是其他方法非常重要这是行不通的。return Ok()return Json()

如果您必须使用 Json 方法(并且别无选择),请参阅此答案/sf/answers/2027235381/


Gre*_*gas 6

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

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

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