Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.

Question Getting Source Generators (System.Text.Json) to work in Unity 2021.3

Discussion in 'Testing & Automation' started by jni97, Mar 28, 2023.

  1. jni97


    May 26, 2015
    Hey, in the past few days I've been trying to get the System.Text.Json package from nuget to work with the included source generators to generate serialization code for some classes.
    The System.Text.Json package was added as net.standard 2.0 dll (and all dependencies too) and I'm using Unity 2021.3.18.

    To get the source generator to work, I followed this page from the official docs:
    which states that:
    I tried pretty much all versions from 6.0.0-preview.1.21102.12 to 7.0.2

    However, while the custom source generator and the example with ErrorProne.NET work without any issues, when I try to use any version of the System.Text.Json generators, it only works within visual studio, but unity doesnt recognize the generated files and therefore complains about missing implementations which prevents compilation. It's weird because the custom source generator from the example also generates a file, which is detected and compiled.

    This is the code that uses the generator to generate the serialization code for a simple class:
    (Works in a regular .net application and visual studio can also compile without problems)
    Code (CSharp):
    1. [System.Serializable]
    2. public class Data
    3. {
    4.     public int x = 7;
    5. }
    7. [JsonSerializable(typeof(Data))]
    8. internal partial class MyJsonContext : JsonSerializerContext
    9. {
    11. }
    I can also see the generated code in visual studio which contains the required overrides for the abstract JsonSerializerContext class and build it there.

    However, the errors in Unity's console indicate that unity doesnt 'see' the generated file, because the generated overrides are missing:
    Is there any way to hint the generated files to unity or something else I could try?

    Example project which contains both example from the docs and System.Text.Json version 6.0.0 is attached.
    Oh, and switching to Unity 2022.2.12 fixes the problem, but unfortunately I have to use the 2021.3 LTS version

    Attached Files:

  2. stephyswe


    Aug 23, 2017
    Can you tell more specific what you trying to do?
    I'm asking, cause, I'm using JSON in Saving data. And I been able to handle JSON data load/fetch from file. Plus added it into a test. I might be able to help you if you can tell what you trying to do.

    A Hint: I'm using NewtonSoft.Json.dll

    Attached Files: