Error deserializing JSON credential Data C# Google Sheets API

5.9k views Asked by At

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?

3

There are 3 answers

0
Hanny On BEST ANSWER

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.

3
Taki On

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);

1
abielita On

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.