Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FLURL: mapping property names

Tags:

c#

flurl

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>>();
like image 550
Aetherix Avatar asked Mar 24 '26 10:03

Aetherix


1 Answers

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; }
}
like image 96
Todd Menier Avatar answered Mar 26 '26 22:03

Todd Menier