C# 获取错误System.InvalidOperationException:反序列化JSON凭据数据时出错
我试图从xamarin C#android应用程序代码调用google cloud vision api。 我已经设置了环境变量,但仍然无法调用api。 所以我决定通过传递凭证json文件来调用它,但现在反序列化json凭证数据时出现错误 这是我的密码C# 获取错误System.InvalidOperationException:反序列化JSON凭据数据时出错,c#,android,visual-studio,xamarin.forms,xamarin.android,C#,Android,Visual Studio,Xamarin.forms,Xamarin.android,我试图从xamarin C#android应用程序代码调用google cloud vision api。 我已经设置了环境变量,但仍然无法调用api。 所以我决定通过传递凭证json文件来调用它,但现在反序列化json凭证数据时出现错误 这是我的密码 string jsonPath = @"C:/Users/abcde/Documents/AndroidApp/My Project-d38b212eadaf.json"; var credential = Google
string jsonPath = @"C:/Users/abcde/Documents/AndroidApp/My Project-d38b212eadaf.json";
var credential = GoogleCredential.FromJson(jsonPath);
var channel = new Grpc.Core.Channel(ImageAnnotatorClient.DefaultEndpoint.ToString(), credential.ToChannelCredentials());
var client = ImageAnnotatorClient.Create(channel);
var image = Image.FromFile(@"C:/Users/abcde/Documents/AndroidApp/bg.jpg");
var response = client.DetectLabels(image);
foreach (var annotation in response)
{
if (annotation.Description != null)
Console.WriteLine(annotation.Description);
}
像
C:/Users/abcde/Documents/AndroidApp/My Project-d38b212eadaf.json这样的路径永远不会起作用。这是一个Windows文件系统
此外,您必须从设备或模拟器开始推理。该设备不能仅访问Windows文件系统并获取该文件。您必须以某种方式在设备上获取该文件,并使用.NET中的path
对象导航到正确的路径。甚至可能通过依赖服务来获得每个平台的正确路径
这有意义吗
var credential = GoogleCredential.FromJson(jsonPath);
不正确,因为需要JSON字符串,而不是JSON文件的路径:
/// <summary>
/// Loads credential from a string containing JSON credential data.
/// <para>
/// The string can contain a Service Account key file in JSON format from the Google Developers
/// Console or a stored user credential using the format supported by the Cloud SDK.
/// </para>
/// </summary>
public static GoogleCredential FromJson(string json) => defaultCredentialProvider.CreateDefaultCredentialFromJson(json);
//
///从包含JSON凭据数据的字符串加载凭据。
///
///该字符串可以包含来自Google开发者的JSON格式的服务帐户密钥文件
///控制台或使用云SDK支持的格式存储的用户凭据。
///
///
公共静态GoogleCredentialFromJSON(字符串json)=>defaultCredentialProvider.CreateDefaultCredentialFromJson(json);
因此,您需要将文件内容加载到JSON字符串中,然后调用FromJson
,谢谢您的回复。你是对的。我正在尝试从运行在windows机器上的android emulator中的android应用程序访问此文件。我还试图将此文件放在代码内的Assets文件夹中,但仍然无法访问此文件。这可能是一个愚蠢的问题,但这是我的第一个android应用程序,我正在尝试学习使用google vision API进行文件处理和通信。我也尝试过使用google Credential.FromFile(jsonPath),但它仍然无法读取文件。基本上,我正在努力将json文件从windows机器读入运行在emulator中的Android应用程序。我还设置了环境变量,这样我就不需要像现在这样在代码中显式地输入凭证Json文件,但环境变量也没有让我通过身份验证来调用GVision api