0

A third party I am calling returns objects in lower case and with underscores, e.g.

{ "token_type":"bearer", "access_token":"blahblah", "expires_in":3600, "scope":"rsp" }

I want to deserialize this into a Pascal case style class, e.g.

public class OAuthResponse
{
    public string TokenType { get; set; }
    public string AccessToken { get; set; }
    public int ExpiresIn { get; set; }
    public string Scope { get; set; }
}

I have tried setting a custom scope for this but it doesn't work. Here's a failing test:

[Fact]
public void ShouldDeserializeUsingScope()
{
    // Arrange
    using (var scope = JsConfig.BeginScope())
    {
        scope.EmitLowercaseUnderscoreNames = true;
        scope.EmitCamelCaseNames = false;

        var response = "{ \"token_type\":\"bearer\", \"access_token\":\"blahblah\", \"expires_in\":3600, \"scope\":\"rsp\" }";

        // Act
        var oAuthResponse = response.FromJson<OAuthResponse>();

        // Assert
        Assert.Equal("rsp", oAuthResponse.Scope);
        Assert.Equal("blahblah", oAuthResponse.AccessToken); // it fails on this line
    }
}

How can I customize the deserialization?

Matt Frear
  • 52,283
  • 12
  • 78
  • 86

2 Answers2

0

Try using the following

using (JsConfig.With(emitLowercaseUnderscoreNames: true, propertyConvention: PropertyConvention.Lenient))
{
 var OAuthResponseDto = JsonSerializer.DeserializeFromString<OAuthResponse>(JsonResponse);
}
A_m0
  • 974
  • 2
  • 17
  • 45
0

The solution is to use TextCase.SnakeCase.

Here's my passing test:

[Fact]
public void ShouldDeserializeUsingScope()
{
    // Arrange
    using (var scope = JsConfig.BeginScope())
    {
        scope.TextCase = TextCase.SnakeCase;

        var response = "{ \"token_type\":\"bearer\", \"access_token\":\"blahblah\", \"expires_in\":3600, \"scope\":\"rsp\" }";

        // Act
        var oAuthResponse = response.FromJson<OAuthResponse>();

        // Assert
        Assert.Equal("rsp", oAuthResponse.Scope);
        Assert.Equal("blahblah", oAuthResponse.Access_Token);
    }
}
Matt Frear
  • 52,283
  • 12
  • 78
  • 86