curiosity-ai / h5

🚀 The next generation C# to JavaScript compiler
https://h5.rocks
Apache License 2.0
204 stars 29 forks source link

Error using Newtonsoft.Json in H5 project after serialization #95

Open lizhihao132 opened 3 months ago

lizhihao132 commented 3 months ago

Issue Description: I've successfully built and run an H5 project following the instructions on the project's homepage. The project builds without errors using dotnet build, and I can start an HTTP server in the output directory to serve the application. Everything works fine in the browser until I add JSON serialization code to Program.cs.

Steps to Reproduce:

  1. Clone the H5 project from [repository URL].
  2. Follow the build instructions on the project's homepage.
  3. Modify Program.cs to include JSON serialization and deserialization using Newtonsoft.Json.
  4. Build the project with dotnet build.
  5. Start an HTTP server in the output directory and open the application in a web browser.

Expected Behavior: The application should serialize and deserialize a Person object to and from JSON without any errors, and the result should be logged to the console.

Actual Behavior: When opening the web page in the browser, I encounter the following JavaScript error: newtonsoft.json.js:340 Uncaught ctor {$init: {...}, message: 'Operation is not valid due to the current state of the object.', innerException: null, errorStack: Error: Operation is not valid due to the current state of the object.

Program.cs code as follows:

using System;
using H5;
using H5.Core;
using static H5.Core.es5;
using static H5.Core.dom;
using Tesserae;
using static Tesserae.UI;
using Newtonsoft.Json;

namespace demo3
{
    public class Person
    {
        public string Name { get; set; }
        public int Age { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            var person = new Person
            {
                Name = "John Doe",
                Age = 30
            };
            {
                string json = JsonConvert.SerializeObject(person);
                System.Console.WriteLine("Serialized JSON: " + json);

                Person deserializedPerson = JsonConvert.DeserializeObject<Person>(json);
                System.Console.WriteLine("Deserialized Person Name: " + deserializedPerson.Name);
                System.Console.WriteLine("Deserialized Person Age: " + deserializedPerson.Age);
            }

            var hello = TextBlock("Hello world!");
            document.body.appendChild(hello.Render());
        }
    }
}
theolivenbaum commented 1 month ago

Hi @lizhihao132, it could be that you're building the project without reflection. Could you share a minimal project in a repo so we can test?

For reference, this needs to be in the h5.json file for reflection to work:

  "reflection": {
    "disabled": false
  },