我在将 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/