【问题标题】:JsonConvert.DeserializeObject<T>(JsonString) returning all Properties<T> as NullJsonConvert.DeserializeObject<T>(JsonString) 将所有 Properties<T> 返回为 Null
【发布时间】:2013-09-10 21:53:55
【问题描述】:

我在将 JSON 字符串转换为 C# 对象时遇到问题。非常基本但没有得到想要的输出。我做错了什么?

这是我的字符串(由 Google 授权服务器提供)

 {
   "access_token" : "xxxxxxxxxxxxxxxxxxxxxxxxxxx",
   "token_type" : "Bearer",
   "expires_in" : 3600,
   "refresh_token" : "yyyyyyyyyyyyyyyyyyyyyyy"
 }

这是课程:

public class GoogleAuthProperty
{
    public string AccessToken { get; set; }
    public string TokenType { get; set; }
    public long ExpiredIn { get; set; }
    public string RefreshToken { get; set; }
}

我正在这样做:

var prop = JsonConvert.DeserializeObject<GoogleAuthProperty>(responseFromServer);

但在prop的属性列表中没有得到任何值

prop.AccessToken is null;
prop.ToeknType is null;
prop.ExpiredIn is 0;
prop.RefreshToken is null;

参考:

Newtonsoft.Json
Version: 4.5.0.0

【问题讨论】:

标签: c#-4.0 json.net


【解决方案1】:

您的 JSON 中的属性名称与您的类中的属性名称不匹配(因为有下划线),因此您获得的是默认值。您可以通过使用 JsonProperty 属性装饰类中的属性并指定 JSON 中使用的属性名称来解决此问题。

使用这个类进行反序列化

public class SampleResponse
{
    [JsonProperty("access_token")]
    public string AccessToken { get; set; }

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

    [JsonProperty("expires_in")]
    public int ExpiresIn { get; set; }

    [JsonProperty("refresh_token")]
    public string RefreshToken { get; set; }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-12
    • 2018-05-25
    • 1970-01-01
    • 1970-01-01
    • 2011-01-16
    相关资源
    最近更新 更多