'pythonnet use System.Text.Json

I am trying to utilise a .NET6 library that depends on System.Text.Json which is failing to import using pythonnet:

Traceback (most recent call last):
  File "<frozen importlib._bootstrap>", line 991, in _find_and_load
  File "<frozen importlib._bootstrap>", line 961, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
ModuleNotFoundError: No module named 'System'

In python, inspecting the assemblies pythonnet has added by default, it can be seen that it does not ship with the System.Text.Json namespace loaded:

import clr
print("[", ", ".join(clr.ListAssemblies(False)), "]")

Outputs:

[ mscorlib, clrmodule, Python.Runtime, System.Core, System.Configuration, System.Xml, System, __CodeGenerator_Assembly, e__NativeCall_Assembly ]

I then try to add System.Text.Json, which appears to succeed:

import clr
import sys

DOTNET_PATH: str = {YOUR PATH TO .NET6 DLLs}
sys.path.append(DOTNET_PATH)

clr.AddReference("System.Text.Json")
print("[", ", ".join(clr.ListAssemblies(False)), "]")

Outputs:

[ ..., System, System.Text.Json, System.Runtime, ... ]

However, trying to import a class from the namespace:

from System.Text.Json import JsonDocument

Continues to raise:

Traceback (most recent call last):
  File "<frozen importlib._bootstrap>", line 991, in _find_and_load
  File "<frozen importlib._bootstrap>", line 961, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
ModuleNotFoundError: No module named 'System'

(I have also tried adding every .dll that ships with .NET 6.0.1 with no success)

Is there some other mechanism I need to utilise to successfully import from this namespace? (And associated)



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source