Search code examples
c#flurl

FLURL: mapping property names


Is there any way to map non-matching property names when doing ReceiveJson()? For example 'user_name' in JSON should map to 'UserName' in C# object.

List<Person> people = await _settings.Url
    .AppendPathSegment("people")
    .GetAsync()
    .ReceiveJson<List<Person>>();

Solution

  • Updated answer for Flurl.Http 4.0 and beyond:

    Starting with 4.0 (in prerelease as of June 2022), Flurl.Http uses System.Text.Json for serialization, so any of its prescribed methods for customizing property names will work with Flurl:

    using System.Text.Json.Serialization;
    
    public class Person
    {
        [JsonPropertyName("user_name")]
        public string UserName { get; set; }
    }
    

    A Json.NET serializer is available for 4.0 and beyond for those who prefer it, in which case use the approach below.

    For Flurl.Http 3.x and earlier:

    Prior to 4.0, Flurl.Http used Newtonsoft Json.NET, so using that library's serialization attributes, specifically JsonProperty, will work in those versions:

    using Newtonsoft.Json;
    
    public class Person
    {
        [JsonProperty("user_name")]
        public string UserName { get; set; }
    }