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?
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);
}
}