4

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.

Chu Bun
  • 513
  • 1
  • 5
  • 17

1 Answers1

6

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

Ebbelink
  • 574
  • 3
  • 16