简体   繁体   中英

Error deserializing JSON credential Data C# Google Sheets API

I'm currently trying to use a service account to access GoogleSheets API - the problem I am having is with my .json file.

Here is my code:

    try
    {
        string[] scopes = new string[] { SheetsService.Scope.Spreadsheets, SheetsService.Scope.SpreadsheetsReadonly }; // Put your scopes here

        var stream = new FileStream("my_application_secret.json", FileMode.Open, FileAccess.Read);

        var credential = GoogleCredential.FromStream(stream);
        credential = credential.CreateScoped(scopes);

        SheetsService service = new SheetsService(new BaseClientService.Initializer()
        {
            HttpClientInitializer = credential,
            ApplicationName = "myApplication",
        });
        return service;
    }
    catch (Exception ex)
    {
        Console.WriteLine("Create service account myApplicationServiceAccount failed : " + ex.Message);
        throw new Exception("Create ServiceAccount Failed : ", ex);
    }

This kicks off my error which reads:

Create service account myApplicationServiceAccount failed : Error deserializing JSON credential data.

But everything I can find online says that what I have above should work.

Is there something more I have to do with this .json file?

As it turns out - because I'm supporting older versions of .NET (4 and below) I am using a slightly older version of the Google Sheets API.

But the Newtonsoft.JSON package was out of date as well. Updated that and now it's working.

try deserializing the object using Newtonsoft.Json library http://www.newtonsoft.com/json

return Newtonsoft.Json.JsonConvert.DeserializeObject<SheetsService>(service);

but the error is in deserializing JSON credential data, so this might be helpful : credential = Newtonsoft.Json.JsonConvert.DeserializeObject<credential.CreateScoped>(scopes);

You may check on this related GitHub thread . Given workaround is:

install-package Microsoft.Bcl.Build
install-package Microsoft.Bcl.Async
install-package Microsoft.Net.Http

Also, you can follow this tutorial about JSON Serialization/Deserialization in C# and see if you miss something.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM