6

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>>();
Aetherix
  • 2,150
  • 3
  • 24
  • 44

1 Answers1

16

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; }
}
Todd Menier
  • 37,557
  • 17
  • 150
  • 173
  • Hi Todd, this does not work for me. I'm using `PostUrlEncodedAsync` and `ReceiveJson`. When I use the `[JsonProperty("user_name")]`, the property is not filled. However if I name the property `user_name` is it filled. – c.lamont.dev Jun 23 '22 at 14:15
  • 1
    @c.lamont.dev I've updated this answer – Todd Menier Jun 24 '22 at 20:03