Apply JsonConverter attribute on Refit request method

143 views Asked by At

I am developing a UWP app using the Refit library to make HTTP requests to an API that returns JSON data.

I have a custom JsonConverter class NoteDeserializerNet : JsonConverter<List<Note>>.

I am using that JsonConverter class on another class model in the following way:

    public class OverviewResult
    {
        [JsonPropertyName("lessons")]
        public List<Lesson> Lessons { get; set; }

        [JsonPropertyName("notes")]
        [System.Text.Json.Serialization.JsonConverter(typeof(NoteDeserializerNet))]
        public List<Note> NotesResult { get; set; }
    }

In that case I am using that JsonConverter on a property that corresponds to the "notes" object on the API's json response.


I have another API endpoint that returns directly that same notes list but as the root object of the json response.

This is the method to get data from an API using the .NET Refit library:

[Get("/students/{userId}/notes/all")]
Task<List<Note>> GetAllNotes(string userId);

I tried to apply the JsonConverter on the method like this, but it is not supported:

[Get("/students/{userId}/notes/all")]
[System.Text.Json.Serialization.JsonConverter(typeof(NoteDeserializerNet))]
Task<List<Note>> GetAllNotes(string userId);

I know I can use the RefitSettings class to set for every request what JsonConverter to use, but I need a flexible and simple solution like the first example. Possibly using an attribute.


I tried also to make a class that is a subset of the List<Note> type:

[System.Text.Json.Serialization.JsonConverter(typeof(NoteDeserializerNet))]
public class NotesResult : List<Note>
{}

But still it doesn't work for both cases as I would have to return a NotesResult object instead of an universal List<Note> object from my custom NoteDeserializerNet class.

I tried also to find a way to set the property inside of a class as the "root" json path, so that I can use the JsonConverter attribute, but apparently there isn't a simple and straightforward way to do this.

public class NotesResult
{
    //how can I set that property to be seen by the deserializer as the "root" json path?
    [System.Text.Json.Serialization.JsonConverter(typeof(NoteDeserializerNet))]
    public List<Note> Notes { get; set; }
}

How can I apply the JsonConverter directly on one Refit method API call in a simple way, with minimal code?

0

There are 0 answers