Correct the wrong example about JSON source generator in the readme by KodamaSakuno · Pull Request #1983 · reactiveui/refit
What kind of change does this PR introduce?
Correct the wrong example about JSON source generator in the readme.
Other information:
The following code shows the difference.
public class UnitTest
{
private readonly HttpClient _client = new(new MyHttpMessageHandler());
[Fact]
public async Task Test1()
{
Response? response = null;
var options = MyJsonSerializerContext.Default.Options;
var exception = await Record.ExceptionAsync(async () =>
{
response = await _client.GetFromJsonAsync<Response>("http://abc", options);
});
Assert.Null(exception);
Assert.Equal(1234, response?.Code);
}
[Fact]
public async Task Test2()
{
Response? response = null;
var options = new JsonSerializerOptions()
{
TypeInfoResolver = MyJsonSerializerContext.Default,
};
var exception = await Record.ExceptionAsync(async () =>
{
response = await _client.GetFromJsonAsync<Response>("http://abc", options);
});
Assert.IsType<JsonException>(exception);
Assert.StartsWith("The JSON value could not be converted to System.Int32. Path: $.Code", exception.Message);
}
}
public class MyHttpMessageHandler : HttpMessageHandler
{
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
return Task.FromResult(new HttpResponseMessage()
{
Content = new StringContent("{\"Code\": \"1234\"}"),
});
}
}
public class Response
{
public int Code { get; set; }
}
[JsonSourceGenerationOptions(NumberHandling = JsonNumberHandling.AllowReadingFromString)]
[JsonSerializable(typeof(Response))]
public partial class MyJsonSerializerContext : JsonSerializerContext;