Json.NET初始化抛出System.TypeLoadException

时间:2014-11-18 05:55:56

标签: c# .net json.net nuget

我有一个包含两个组件的解决方案:

  • .NET 4.5控制台应用程序(A)。
  • 使用Newtonsoft的Json.NET(B)的PCL库。

只要B使用并引用Json.NET(作为NuGet包),一切正常。但是,只要我从A添加对同一个NuGet包的引用,我就会一直得到:

System.TypeLoadException: Could not load type 'Newtonsoft.Json.SerializationBinder' ...

我跟踪了由NuGet引起的问题,包括两个不同版本的Json.NET程序集:

  • A使用的文件描述设置为 Json.NET
  • B使用的文件描述设置为 Json.NET Portable

显然,一个组件不能被另一个组件替换。我的PCL不再找到它期望的版本,因此例外。

如何配置NuGet,以便两个项目都引用Json.NET可移植版本?

1 个答案:

答案 0 :(得分:4)

我找到了一种解决方法,以确保BA引用相同的 Json.NET Portable 程序集。

默认情况下,NuGet将<HintPath>配置为设置为库的net45版本:

<Reference Include="Newtonsoft.Json, Version=6.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
  <SpecificVersion>False</SpecificVersion>
  <HintPath>..\packages\Newtonsoft.Json.6.0.6\lib\net45\Newtonsoft.Json.dll</HintPath>
</Reference>

这是这场冲突的根源。因此,请将A.csproj文件编辑为:

<Reference Include="Newtonsoft.Json, Version=6.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
  <SpecificVersion>False</SpecificVersion>
  <HintPath>..\packages\Newtonsoft.Json.6.0.6\lib\portable-net45+wp80+win8+wpa81+aspnetcore50\Newtonsoft.Json.dll</HintPath>
</Reference>

有了这个,AB将使用完全相同的程序集。