在请求正文 I 中有一个名为systemDate
的属性。此属性在我的模型中始终设置为0
,我认为这是因为变量类型(long
、double
等),但是在我将请求正文中的名称从systemDate
更改为someDate
并在模型类中从SystemDate
更改为SomeDate
后,该值将按预期从请求正文传递到模型实例。
为什么会发生这种情况,有没有办法保留请求 json 命名并使其将其值传递给模型?
{
"category":"some_category",
"level":5,
"source":"some_source",
"location":"some_location",
"date":2793455394017,
"message":"some_message",
"id":3295830,
"systemDate":1533114073596991534
}
下面是我的模型类的样子:
public class MyModel
{
public MyModel()
{
}
public string Category { get; set; }
public int Level { get; set; }
public string Source { get; set; }
public string Location { get; set; }
public double Date { get; set; }
public string Message { get; set; }
public long Id { get; set; }
public double SystemDate { get; set; }
}
和控制器方法:
[HttpPost(EndpointUrlConstants.MY_ENDPOINT)]
public async Task<IActionResult> DoSomething([FromBody] MyModel myModel)
{
// Some Code
return this.Ok();
}
对于Asp.Net Core
,我们可以通过在Startup
中AddJsonOptions
来配置Json Serialize Settings
。
而这个问题的根本原因与NamingStrategy = new SnakeCaseNamingStrategy()
.
我不确定我是否理解您的问题,但是您可以使用属性控制序列化,即json字符串中的属性名称不必与模型中的属性名称匹配。
public class MyModel
{
public MyModel()
{
}
[JsonProperty("category")]
public string Category { get; set; }
[JsonProperty("level")]
public int Level { get; set; }
[JsonProperty("source")]
public string Source { get; set; }
[JsonProperty("location")]
public string Location { get; set; }
[JsonProperty("date")]
public double Date { get; set; }
[JsonProperty("message")]
public string Message { get; set; }
[JsonProperty("id")]
public long Id { get; set; }
[JsonProperty("systemDate")]
public double SomeDate { get; set; }
}
测试代码,使用 Newtonsoft.Json nuget 包:
string json = @"{
""category"":""some_category"",
""level"":5,
""source"":""some_source"",
""location"":""some_location"",
""date"":2793455394017,
""message"":""some_message"",
""id"":3295830,
""systemDate"":1533114073596991534
}";
MyModel model = JsonConvert.DeserializeObject<MyModel>(json);
对象已正确反序列化。如您所见,模型中SomeDate
属性已映射为与 json 字符串中的systemDate
属性匹配。