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.
  2. Dismiss Notice

Question Dynamic update of C# class object from JSON

Discussion in 'Scripting' started by fabi_s, Oct 19, 2021.

  1. fabi_s

    fabi_s

    Joined:
    Jan 25, 2021
    Posts:
    10
    Hi All,

    I am a C# newbie, and I would like to understand how to create (and update) a C# class object from a JSON file while in play mode. So far, I have used QuickType to convert the file into a C# class. Nevertheless, this is an issue when I need to update my c# class if I use cloud-based multi-user applications that modify the original JSON structure.

    Is there a workaround that allows me to update a c# class from a JSON (with no pre-determined structure) without opening the browser, converting the JSON file, importing it into VS code, and restarting the game?
     
  2. RadRedPanda

    RadRedPanda

    Joined:
    May 9, 2018
    Posts:
    1,593
    I don't believe there is an easy way to do this, as you would basically need to compile code at runtime (since we don't know the class structure beforehand). Would you mind sharing what you're trying to accomplish long-term? We might be able to supply a different solution to your problem.
     
  3. Stardog

    Stardog

    Joined:
    Jun 28, 2010
    Posts:
    1,887
    You can try dynamic classes, but you will lose autocomplete. You just need to download the new json and convert it to a string.

    Code (csharp):
    1.           using System.Dynamic;
    2.           using Newtonsoft.Json;
    3.  
    4.           ...
    5.  
    6.           string json = @"{
    7.          'Name': 'Bad Boys',
    8.          'ReleaseDate': '1995-4-7T00:00:00',
    9.          'Genres': [
    10.            'Action',
    11.            'Comedy'
    12.          ],
    13.          'Test': 25
    14.        }";
    15.  
    16.         dynamic m = JsonConvert.DeserializeObject<dynamic>(json, new JsonSerializerSettings()
    17.         {
    18.             Formatting = Formatting.Indented,
    19.             ReferenceLoopHandling = ReferenceLoopHandling.Ignore
    20.         });
    21.  
    22.         Debug.Log($"{m.Name} - {m.ReleaseDate} - {m.Test}")
     
  4. fabi_s

    fabi_s

    Joined:
    Jan 25, 2021
    Posts:
    10
    I understand. I decided to fix the structure of the json and avoid any changes in the file. I will use QuickType to map the class object from the text file once before compiling and building the app. Thank you for the info.