c#-4.0 - JsonConvert.DeserializeObject<T>(JsonString) 将所有 Properties<T> 返回为 Null

标签 c#-4.0 json.net

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

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

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

这是类(class):
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

最佳答案

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

关于c#-4.0 - JsonConvert.DeserializeObject<T>(JsonString) 将所有 Properties<T> 返回为 Null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18711721/

相关文章:

c# - 自定义转换器重写 ContractResolver

c# - JSON.Net - 反序列化 - 属性值中的下划线变成空格

c# - JSON 反序列化 - 使用 JSON.NET 将数组索引映射到属性

c# - 在 JSON.NET 中反序列化 IList<Interface>

IronPython 中质量评估表达式的性能

c# - VB.NET下的Late Binding Magic转换为C#

c#-4.0 - 在 C# 中使用 7zip.exe 压缩多个文件

f# - 使用 json.net 和包含 @ 符号的 json 属性反序列化为 F# 类型

c# - "If foo isn' t null 在 C# 中有什么好的语法,返回它的属性,否则为 null"

c# - 如何使用 C# 4 中的 TPL 创建常量 Processing "Flow"