在webapi中认证后反序列化json对象

3no*_*ot3 2 c# json deserialization

我正在向 webapi 2.0“www.someurl.com\token”发送一个发布请求,如下 -

"username": "someone@gmail.com", "password": "somepassword", "grant_type" : "password"
Run Code Online (Sandbox Code Playgroud)

如果 webapi 可以进行身份​​验证,它会向我发送一个包含以下字段的不记名令牌 -

"{\"access_token\":\"...the token...\",\"token_type\":\"bearer\",\"expires_in\":1209599,\"userName\":\"someone@gmail.com\",\".issued\":\"Mon, 05 Nov 2018 13:59:10 GMT\",\".expires\":\"Mon, 19 Nov 2018 13:59:10 GMT\"}"
Run Code Online (Sandbox Code Playgroud)

我想知道是否可以直接将其反序列化为类对象,可能是这样的Json.Convert<Object Type>(data)。我总是可以使用自定义对象来执行此操作,但我正在搜索是否可以使用某些标准类类型。

Woo*_*193 5

你需要问自己:你想用这个对象做什么?仅反序列化到对象将意味着如果不使用反射,您将无法访问任何属性,这充其量只会是混乱的。相反,声明一个类:

public sealed class BearerToken
{
    [JsonProperty(PropertyName = "access_token")]
    public string AccessToken { get; set; }

    [JsonProperty(PropertyName = "token_type")]
    public string TokenType { get; set; }

    [JsonProperty(PropertyName = "expires_in")]
    public int ExpiresInMilliseconds { get; set; }

    [JsonProperty(PropertyName = "userName")]
    public string Username { get; set; }

    [JsonProperty(PropertyName = ".issued")]
    public DateTimeOffset? IssuedOn { get; set; }

    [JsonProperty(PropertyName = ".expires")]
    public DateTimeOffset? ExpiresOn { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

然后你就可以这样做JsonConvert.DeserializeObject<BearerToken>(data);,这会给你一个完整的BearerToken对象,然后你可以使用它。

请注意,这里的魔力在于属性JsonProperty,它将通知转换器哪个字段去哪里。您还可以使用这样的工具为您自动生成类。