在执行ReceiveJson()
时,是否有办法映射不匹配的属性名称?例如,JSON中的'user_name'应该映射到C#对象中的'UserName'。
List<Person> people = await _settings.Url
.AppendPathSegment("people")
.GetAsync()
.ReceiveJson<List<Person>>();
从4.0开始(截至2022年6月预发布),Flurl.Http使用System.Text.Json进行序列化,因此其推荐的任何方法来自定义属性名称都可以与Flurl一起使用:
using System.Text.Json.Serialization;
public class Person
{
[JsonPropertyName("user_name")]
public string UserName { get; set; }
}
对于那些偏爱使用Json.NET的人,可以在4.0及以上版本中使用Json.NET序列化程序。如果是使用Flurl.Http 3.x或更早版本,则可以使用Newtonsoft Json.NET库的序列化属性,特别是JsonProperty属性:
using Newtonsoft.Json;
public class Person
{
[JsonProperty("user_name")]
public string UserName { get; set; }
}