Toto
Toto

Reputation: 972

Use Newtonsoft library in NetStandard 2.0 class library

I am developing a class library based on the NetStandard 2.0 framework for multiple platform compatibility sakes, and I need to serialize and deserialize objects. So I added a reference to the Newtonsoft library.

The problem is that I have the following exception at runtime:

System.IO.FileNotFoundException: 'Could not load file or assembly 'System.ComponentModel.Annotations, Version=4.2.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified.'

I tried to manually add a reference to the System.ComponentModel.Annotations version 4.2.0.0 but this version is not available.

Is there a way to use Newtonsoft with NetStandard 2.0, or an alternative to perform serialization/deserialization operations?

Update: it seems that adding a reference to System.ComponentModel.Annotations" Version="4.4.1" and rebuilding the solution fixed the problem.

Here is the content of my csproj file:

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <TargetFramework>netstandard2.0</TargetFramework>
  </PropertyGroup>

    <ItemGroup>
      <PackageReference Include="Newtonsoft.Json" Version="10.0.3" />
      <PackageReference Include="System.ComponentModel.Annotations" Version="4.4.1" />
    </ItemGroup>
</Project>

Upvotes: 8

Views: 10284

Answers (2)

yoel halb
yoel halb

Reputation: 12711

The solution of @user9200027 to add a reference didn't work for me. However referencing as content does work, but it has the side effect of showing up in the solution explorer file list.

But note that if targeting multiple frameworks one should add a condition for the .net standard framework, otherwise it will override the file for the non .net standard frameworks as well.

Here is a sample .csproj entry:

<Content Condition="$(TargetFramework)=='netstandard2.0'"
    Include="$(NuGetPackageRoot)\newtonsoft.json\12.0.2\lib\netstandard2.0\Newtonsoft.Json.dll">
  <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
  <CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
  <Visible>False</Visible>
</Content>

Upvotes: 1

user9200027
user9200027

Reputation:

So I have been looking at referencing Newtonsoft.Json from the .NETStandard 2.0. It's all there and ready in version Newtonsoft.Json.11.0.2.

~/packages/Newtonsoft.Json.11.0.2/

enter image description here

Just reference it in csproj like so...

<Reference Include="Newtonsoft.Json">
  <HintPath>..\APAS.WebInterface\packages\Newtonsoft.Json.11.0.2\lib\netstandard2.0\Newtonsoft.Json.dll</HintPath>
</Reference>

Upvotes: 4

Related Questions