【问题标题】:getting error System.InvalidOperationException: Error deserializing JSON credential data收到错误 System.InvalidOperationException:反序列化 JSON 凭据数据时出错
【发布时间】:2018-09-01 09:24:05
【问题描述】:

我正在尝试从 xamarin C# android 应用程序代码调用 google cloud vision api。 我已经设置了环境变量,但我仍然无法调用 api。 所以我决定通过传递凭证 json 文件来调用它,但现在我在反序列化 JSON 凭证数据时遇到错误

这是我的代码

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# android visual-studio xamarin.forms xamarin.android


    【解决方案1】:

    C:/Users/abcde/Documents/AndroidApp/My Project-d38b212eadaf.json 这样的路径永远行不通。这是一个 Windows 文件系统。

    此外,您必须从设备或模拟器开始推理。该设备不能只访问您的 Windows 文件系统并获取该文件。您必须以某种方式在您的设备上获取该文件,并使用 .NET 中的 Path 对象导航到正确的路径。甚至可能通过依赖服务来获得每个平台的正确路径。

    这有意义吗?

    【讨论】:

    • 感谢您的回复。你说的对。我正在尝试从在 Windows 机器上运行的 android 模拟器中运行的 android 应用程序访问此文件。我还尝试将此文件放在代码内的 Assets 文件夹中,但我仍然无法访问此文件。这可能是一个愚蠢的问题,但这是我的第一个 android 应用程序,我正在尝试学习文件处理和与 google vision API 的通信。
    【解决方案2】:
    var credential = GoogleCredential.FromJson(jsonPath);
    

    不正确,因为 FromJson 需要 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 字符串中,然后然后调用FromJson

    【讨论】:

    • 我也尝试过使用 GoogleCredential.FromFile(jsonPath) 但它仍然无法读取文件。基本上我正在努力将 json 文件从 Windows 机器读取到在模拟器中运行的 Android 应用程序中。我还设置了环境变量,这样我就不需要像现在这样在代码中显式地输入凭据 Json 文件,但是环境变量也没有让我通过身份验证来调用 GVision api
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-16
    • 1970-01-01
    • 2020-07-03
    • 2018-10-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多