我在一个Xamarin.Forms应用程序中对谷歌进行身份验证。一旦通过身份验证,我想检索用户电子邮件,并使用我改编自此博客的代码,用于检索电子邮件的代码:
public class GoogleProfile
{
[Preserve]
[JsonConstructor]
public GoogleProfile() { }
public string sub { get; set; }
public string name { get; set; }
public string given_name { get; set; }
public string profile { get; set; }
public string picture { get; set; }
public string email { get; set; }
public string email_verified { get; set; }
public string locale { get; set; }
}
public class GoogleService
{
public async Task<string> GetEmailAsync(string tokenType, string accessToken)
{
var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(tokenType, accessToken);
var json = await httpClient.GetStringAsync("https://www.googleapis.com/oauth2/v3/userinfo");//https://www.googleapis.com/userinfo/email?alt=json");
var profile = JsonConvert.DeserializeObject<GoogleProfile>(json);
return profile.email;
}
}
现在,在最后一行有一个断点,return profile.email我已经“看到”了这样的 json 文件:
{
"sub": "",
"name": "",
"given_name": "",
"profile": "",
"picture": "",
"email": "",
"email_verified": "",
"locale": "",
}
显然,引号之间是数据。
我对 JSon 不太习惯,但读到这里我认为格式很简单"nameOfProperty":"ValueOfProperty",所以我做了GoogleProfile对象。
我也读到了这些属性[Preserve]并且[JsonConstructor]是必要的,因此链接器在编译时不仅仅是“删除”空的构造函数。
没有例外,也没有明显的问题,但是如果我在最后return profile.email;一行放一个断点,我可以看到该json对象包含所有数据并且非常好,但是该profile对象只有email具有值的属性null...
我不明白:其他属性发生了什么?甚至可能吗?你知道,你用一堆属性编写了一个对象,但创建的对象只有其中一个属性吗?如果对象的所有属性的值都为 null,那好吧,但是其他属性到哪里去了?
可以肯定的是,我已经清理并重建了项目和解决方案,我已经删除了文件夹,bin然后obj再次清理和重建......我已经完成了显而易见的事情。
事情是,正如您在我之前提到的博客中看到的那样,首先我没有使用GoogleProfile对象,我只是复制了博客中的对象......只有一个名为email. 视觉工作室或xamarin或其他东西是否有可能被窃听并且更改没有得到反映?我对此表示怀疑,因为我已经更改了GetStringAsync方法中使用的 URI,它确实得到了反映,但是,我不知道。
PD:与此同时,我将 JSON 直接解析为普通字符串,它是一个简单的对象,我只需要电子邮件,但是,如果我不得不以这种方式解析它而不是仅仅解析它,那就太可惜了反序列化它。
编辑: 正如 Skin 在我使用过的评论中所建议的那样http://jsonutils.com/
其中一个属性是 bool(当然),所以我改变了它,现在的对象是:
public class GoogleProfile
{
[Preserve]
[JsonConstructor]
public GoogleProfile() { }
public string sub { get; set; }
public string name { get; set; }
public string given_name { get; set; }
public string profile { get; set; }
public string picture { get; set; }
public string email { get; set; }
public bool email_verified { get; set; }
public string locale { get; set; }
}
但这并没有改变结果,仍然发生同样的事情。断点处的结果图像:

