我呼叫的第三方返回小写且带有下划线的对象,例如
{ "token_type":"bearer", "access_token":"blahblah", "expires_in":3600, "scope":"rsp" }
我想将此反序列化为Pascal案例样式类,例如
public class OAuthResponse
{
public string TokenType { get; set; }
public string AccessToken { get; set; }
public int ExpiresIn { get; set; }
public string Scope { get; set; }
}
我尝试为此设置自定义范围,但是它不起作用。测试失败:
[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
}
}
如何自定义反序列化?
答案 0 :(得分:0)
尝试使用以下
using (JsConfig.With(emitLowercaseUnderscoreNames: true, propertyConvention: PropertyConvention.Lenient))
{
var OAuthResponseDto = JsonSerializer.DeserializeFromString<OAuthResponse>(JsonResponse);
}
答案 1 :(得分:0)
解决方案是使用TextCase.SnakeCase
。
这是我的及格考试:
[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);
}
}