'Google.Apis.Json.NewtonsoftJsonSerializer'的类型初始值设定项引发了异常

时间:2013-11-10 17:39:18

标签: c#-4.0 oauth-2.0

我正在使用Oauth 2访问Google Analytics数据。当我尝试执行以下代码时,会发生以下错误:

  

'Google.Apis.Json.NewtonsoftJsonSerializer'的类型初始值设定项   抛出异常。

这是我的代码:

string clientid = "my client id";
string clientsecret = "my client secret";

var client = new WebServerClient(GoogleAuthenticationServer.Description, clientid, clientsecret);

var auth = new OAuth2Authenticator<WebServerClient>(client, Authenticate);

var asv = new Google.Apis.Analytics.v3.AnalyticsService(new BaseClientService.Initializer()
{
    Authenticator = auth,
});

var request = asv.Data.Ga.Get("ga:" + "my ProfileID", "2012-01-01", "2012-02-20", "ga:visits");
var report = request.Fetch();

private IAuthorizationState Authenticate(WebServerClient client)
{
    IAuthorizationState state = new AuthorizationState(new string[] {}) { RefreshToken = "my refresh token" };
    client.RefreshToken(state);
    return state;
}

4 个答案:

答案 0 :(得分:2)

我导入的命名空间using Newtonsoft.Json 是旧版本。然后我导入了新版Newtonsoft.Json (Version=4.0.2.0)。现在它的工作...........

答案 1 :(得分:2)

我已经记录了我为YouTube Data API v3解决此问题的经验,请参阅以下详细信息:

仅供参考我使用的是Visual Studio 2012,而.Net解决方案由Asp.NET Web应用程序和类库项目组成。我在类库项目中引用了Google Data API v3。

  • 确保您已从Nuget经理安装了最新的Google.Apis.YouTube.v3客户端库。

  • Nuget经理更新所有待处理的包。

  • 从bin文件夹中删除所有文件(来自两个项目)。

  • 如果存在,请从Web应用程序项目中删除Newtonsoft.Json引用。

  • 从Web应用程序项目packages.config中删除以下行(如果存在):

    <package id="Newtonsoft.Json" version="4.0.8" targetFramework="net45" />
    
  • 将以下内容添加到Web应用程序项目的web.config中:

    <runtime>
      <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
        <dependentAssembly>
          <assemblyIdentity name="System.Net.Http.Primitives" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
          <bindingRedirect oldVersion="0.0.0.0-4.2.20.0" newVersion="4.2.20.0" />
        </dependentAssembly>
        <dependentAssembly>
          <assemblyIdentity name="log4net" publicKeyToken="669e0ddf0bb1aa2a" culture="neutral" />
          <bindingRedirect oldVersion="0.0.0.0-1.2.13.0" newVersion="1.2.13.0" />
        </dependentAssembly>
        <dependentAssembly>
          <assemblyIdentity name="Microsoft.Threading.Tasks.Extensions.Desktop" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
          <bindingRedirect oldVersion="0.0.0.0-1.0.168.0" newVersion="1.0.168.0" />
        </dependentAssembly>
        <dependentAssembly>
          <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
          <bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
        </dependentAssembly>
      </assemblyBinding>
    </runtime>
    

答案 2 :(得分:0)

通过以下代码,这可能对您有所帮助,对我来说工作正常。

    static void Main(string[] args)
    {

        try
        {
            // Setting up webserver client by providing your application clientid,client secretid which are we registered in google api (cloud) console.
            var client = new WebServerClient(GoogleAuthenticationServer.Description, "Your ClientID", "Client Secret");

            // Authenticating the Web server client and GA account by passing the long lived refresh token 
            var auth = new OAuth2Authenticator<WebServerClient>(client, Authenticate);

            // Initialize the Google analytics service.
            // Set the auth parameter to Authenticator in Google analytics service instance
            var asv = new Google.Apis.Analytics.v3.AnalyticsService(new BaseClientService.Initializer()
            {
                Authenticator = auth
            });

            // Preparing the query request  for Google api
            string queryDate = "";
            queryDate = DateTime.Today.AddDays(-1).ToString("yyyy-MM-dd");
            var request = asv.Data.Ga.Get("ga:" + "Your profileid", queryDate, queryDate, "ga:visits,ga:newVisits,ga:bounces,ga:pageviews,ga:timeOnSite,ga:transactionsPerVisit");
            // Adding dimensions
            request.Dimensions = "ga:date";
            // Fecthing data
            var data = request.Fetch();



        }

        catch (Exception ex)
        {

        }
    }




    private static IAuthorizationState Authenticate(WebServerClient client)
    {
        // The refresh token which application captures called as long lived refresh token, and will be used for gat new access token in future.
        // In Json format access token and refresh token will be captured and saved in database when user allowd our application to access his analytics data.
        // Next time when we are going to access the google analytics data for that user load the refresh token
        IAuthorizationState state = new AuthorizationState(new string[] { }) { RefreshToken = "your refresh token" };

        // Refresh the access token by passing the long lived refreshed token
        client.RefreshToken(state);

        // return the IAutherizationSate result
        return state;
    }

注意:在使用这些方法之前,您必须获取刷新令牌

答案 3 :(得分:0)

我遇到了这个错误,但是我的解决方法有所不同。我使用的是Visual Studio 2017,并且安装了Newtonsoft.Json的当前版本(当时)(11.0.2)。当我安装当前版本的Google.Apis(1.35.1)时,收到错误消息“ Google.Apis.Json.NewtonsoftJsonSerializer的类型初始化器抛出异常”。查看内部异常信息时,我发现Google.Apis期望使用Newtonsoft.Json版本10。我删除了Newtonsoft和Google.Apis,然后通过nuget重新安装了google.apis。 Newtonsoft.Json的版本10也已安装,错误消失了。

如果任何人也有此错误,请确保已实际安装google api预期的Newtonsoft版本。