"Unable to find constructor" 在 Uno WASM 中序列化 JSON 时

"Unable to find constructor" when serializing JSON in Uno WASM

我一直在寻找 WASM 中出现的错误:

Newtonsoft.Json.JsonSerializationException: Unable to find a constructor to use for type Hqub.MusicBrainz.API.Entities.Recording. 
A class should either have a default constructor, one constructor with arguments or a constructor marked with the JsonConstructor attribute. Path 'recordings[0].id', line 1, position 86.

我目前拥有的最佳线索是 this old blog post 关于 Xamarin for Android 使用的 Mono 运行时:,其中指出:

In the 'Android options' tab of the project properties, there is a 'linker' tab. Is the selected option in the 'Linking' dropdown "Sdk Assemblies only" or is it "Sdk and user assemblies"?

If it is the latter, the parameterless constructor is skipped when linking, because no use is detected. So change it to "Sdk Assemblies only".

我试过切换到 System.Text.Json,结果出现了类似的错误:

 System.NotSupportedException: Deserialization of reference types without parameterless constructor is not supported. Type 'Hqub.MusicBrainz.API.Entities.Recording'
   at System.Text.Json.ThrowHelper.ThrowNotSupportedException_DeserializeCreateObjectDelegateIsNull (System.Type invalidType) <0x4b45408 + 0x0004e> in <filename unknown>:0 
   at System.Text.Json.JsonSerializer.HandleStartObject (System.Text.Json.JsonSerializerOptions options, System.Text.Json.ReadStack& state) <0x4b17ec0 + 0x001f6> in <filename unknown>:0 
   at System.Text.Json.JsonSerializer.ReadCore (System.Text.Json.JsonSerializerOptions options, System.Text.Json.Utf8JsonReader& reader, System.Text.Json.ReadStack& readStack) <0x4b16610 + 0x0017c> in <filename unknown>:0 
   at System.Text.Json.JsonSerializer.ReadCore (System.Text.Json.JsonReaderState& readerState, System.Boolean isFinalBlock, System.ReadOnlySpan`1[T] buffer, System.Text.Json.JsonSerializerOptions options, System.Text.Json.ReadStack& readStack) <0x4b15610 + 0x00056> in <filename unknown>:0 
   at System.Text.Json.JsonSerializer.ReadAsync[TValue] (System.IO.Stream utf8Json, System.Type returnType, System.Text.Json.JsonSerializerOptions options, System.Threading.CancellationToken cancellationToken) <0x4abbcc8 + 0x00356> in <filename unknown>:0 
   at System.Threading.Tasks.ValueTask`1[TResult].get_Result () <0x4b71b40 + 0x00036> in <filename unknown>:0 
   at Hqub.MusicBrainz.API.MusicBrainzClient.GetAsync[T] (System.String url) <0x4924a28 + 0x006e0> in <filename unknown>:0 

我试过在每个 class 中创建构造函数并将它们标记为 internal,这似乎已将错误消息转移到不同的类型,但没有解决它。

感谢任何帮助

是的,这是一个错误,表明剥离未使用代码的链接器已经剥离了构造函数,因为它不知道 Json.NET(或 System.Text.Json)正在通过反射使用它。

没有与“仅 Sdk 程序集”选项完全等效的选项(因为本身没有 'Wasm Sdk'),但您只需添加包含 Recording 类型的程序集作为条目LinkerConfig.xml 在 Wasm 平台头文件夹的根目录下。

例如:

<assembly fullname="Hqub.MusicBrainz.API />

(您可以在 'Properties' 选项卡中查看包含该类型的项目的程序集名称。)