[wasm] Use source generator for results data json serialization (#89177)
authorRadek Doulik <radek.doulik@gmail.com>
Wed, 19 Jul 2023 13:26:54 +0000 (15:26 +0200)
committerGitHub <noreply@github.com>
Wed, 19 Jul 2023 13:26:54 +0000 (15:26 +0200)
This fixes problem with posting results, where we crashed with:

    MONO_WASM:    at System.Text.Json.ThrowHelper.ThrowInvalidOperationException_JsonSerializerOptionsNoTypeInfoResolverSpecified()
       at System.Text.Json.JsonSerializerOptions.MakeReadOnly()
       at System.Text.Json.JsonSerializerOptions.ConfigureForJsonSerializer()
       at System.Text.Json.JsonSerializer.GetTypeInfo(JsonSerializerOptions , Type )
       at System.Text.Json.JsonSerializer.GetTypeInfo[JsonResultsData](JsonSerializerOptions )
       at System.Text.Json.JsonSerializer.Serialize[JsonResultsData](JsonResultsData , JsonSerializerOptions )
       at Sample.Test.GetJsonResults()
       at Sample.Test.GetFullJsonResults()
       at Sample.Test.__Wrapper_GetFullJsonResults_234275758(JSMarshalerArgument* __arguments_buffer)
    ManagedError@http://localhost:8781/_framework/dotnet.runtime.js:3:29628
    vr@http://localhost:8781/_framework/dotnet.runtime.js:3:34757
    Ao@http://localhost:8781/_framework/dotnet.runtime.js:3:52015
    To/U</<@http://localhost:8781/_framework/dotnet.runtime.js:3:50790
    init@http://localhost:8781/main.js:118:19
    setTimeout handler*yieldBench/<@http://localhost:8781/main.js:129:49
    yieldBench@http://localhost:8781/main.js:129:16
    init@http://localhost:8781/main.js:108:45
    setTimeout handler*yieldBench/<@http://localhost:8781/main.js:129:49
    yieldBench@http://localhost:8781/main.js:129:16
    init@http://localhost:8781/main.js:108:45

src/mono/sample/wasm/browser-bench/Program.cs

index 2d4278f..6c3f6d4 100644 (file)
@@ -7,6 +7,7 @@ using System.Collections.Generic;
 using System.IO;
 using System.Text;
 using System.Text.Json;
+using System.Text.Json.Serialization;
 using System.Text.RegularExpressions;
 using System.Runtime.CompilerServices;
 using System.Threading.Tasks;
@@ -209,11 +210,14 @@ namespace Sample
             public DateTime timeStamp;
         }
 
+        [JsonSourceGenerationOptions(IncludeFields = true, WriteIndented = true)]
+        [JsonSerializable(typeof(JsonResultsData))]
+        partial class ResultsSerializerContext : JsonSerializerContext { }
+
         string GetJsonResults()
         {
-            var options = new JsonSerializerOptions { IncludeFields = true, WriteIndented = true };
             var jsonObject = new JsonResultsData { results = results, minTimes = minTimes, timeStamp = DateTime.UtcNow };
-            return JsonSerializer.Serialize(jsonObject, options);
+            return JsonSerializer.Serialize(jsonObject, ResultsSerializerContext.Default.JsonResultsData);
         }
 
         private void PrintJsonResults()