Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Refit AliasAs does not work for deserialize

Just wonder what is the proper way to use AliasAs in deserializing a response in ReFit? The code below will correctly parse a response if the variable name in the model is the same as in the response, but the returned value will be null if the names are different.

Model class:

using Refit;
using System;
using System.Text.Json;
using System.Text.Json.Serialization;

namespace TestRefit
{
    public class PriceModel
    {
        [AliasAs("disclaimer")]
        public string? Disclaimer123 { get; set; } 
        // "Disclaimer" or "disclaimer" work, but not "DisclaimerWhatever", "Disclaimer123", ....

        [AliasAs("charName")]
        public string? ChartName { get; set; }

    }
}

Interface class:

using Refit;
using System.Threading.Tasks;

namespace TestRefit
{
    public interface IPrice
    {
        [Get("/v1/bpi/currentprice.json")]
        Task<PriceModel> GetPrice();
    }
}

Invocation:

public async void LoadPrice()
{
    var iPriceClient = RestService.For<IPrice>("https://api.coindesk.com");
    CurPrice = await iPriceClient.GetPrice();
    Debug.WriteLine($"**** Check: {CurPrice?.ChartName}, {CurPrice?.Disclaimer123}.");
    // Output: **** Check: Bitcoin, . 
    return;
}

I found this article https://github.com/reactiveui/refit/issues/450 . Has anything changed since? By the way, older version of Refit that uses the NewSoftJson equivalence [JsonProperty] seems to work without any problem.

like image 881
Chu Bun Avatar asked Oct 29 '25 09:10

Chu Bun


1 Answers

Refit provides 2 implementations out of the box. The default is the SystemTextJsonContentSerializer from System.Text.Json. The alternative implementation is NewtonsoftJsonContentSerializer which comes from Newtonsoft.Json. You can read here how to setup Refit Newtonsoft

So in order to deserialize your response you should decide which one to use first.

If you decide to use SystemTextJsonContentSerializer from System.Text.Json you should use the [JsonPropertyName("YourJsonPropertyNameHere")] attribute as you can read here

If end up using NewtonsoftJsonContentSerializer from Newtonsoft.Json you should use the [JsonProperty("YourJsonPropertyNameHere")]. More on the JsonPropertyAttribute can be read here

like image 109
Ebbelink Avatar answered Oct 31 '25 02:10

Ebbelink



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!