Search Unity

  1. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Resolved JSON to Scriptable object

Discussion in 'Scripting' started by XukeLho, Oct 29, 2021.

  1. XukeLho

    XukeLho

    Joined:
    Dec 30, 2014
    Posts:
    199
    Hey guys, at my job we are using JSON configurations stored in a DB that we download on demand (and obviously deserialize to a class). We would like to upgrade our system to instead of downloading and parsing the JSON, just receive the ID of the file and download the Scriptable Object instead. The problem is, we have to rebuild our entire database into scriptable objects. This is something we don't want to do by hand because we have 1000+ files.
    So, is there a way to create those 1000+ files as scriptable objects from json, with code? Everything I've found so far is the other way around, from SO to JSON.
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,292
    Yes!

    Steps to success:

    - iterate your JSONs

    - for each SO, create the SO yourself with ScriptableObject.CreateInstance<T>();

    - populate the SO instance with your JSON (not create it, populate it with data)

    - write it to the AssetDatabase.

    Depending on your data, you may need a real JSON package instead of Unity's tiny/lite package.

    Problems with Unity "tiny lite" built-in JSON:

    In general I highly suggest staying away from Unity's JSON "tiny lite" package. It's really not very capable at all and will silently fail on very common data structures, such as Dictionaries and Hashes and ALL properties.

    Instead grab Newtonsoft JSON .NET off the asset store for free, or else install it from the Unity Package Manager (Window -> Package Manager).

    https://forum.unity.com/threads/jso...-not-working-as-expected.722783/#post-4824743

    https://assetstore.unity.com/packages/tools/input-management/json-net-for-unity-11347

    Also, always be sure to leverage sites like:

    https://jsonlint.com
    https://json2csharp.com
    https://csharp2json.io

    PS: for folks howling about how NewtonSoft JSON .NET will "add too much size" to your game, JSON .NET is like 307k in size, and it has the important advantage that it actually works the way you expect a JSON serializer to work in the year 2021.
     
  3. XukeLho

    XukeLho

    Joined:
    Dec 30, 2014
    Posts:
    199
    Aiiight!
    I was missing the AssetDatabase
    Worked like a charm!
    Thanks
     
    Kurt-Dekker likes this.
  4. Blenderik

    Blenderik

    Joined:
    May 14, 2013
    Posts:
    142
    I don't know how populate works in Newtonsoft, but if you are using Unity's Json deserializer, It might be worth mentioning:
    Code (CSharp):
    1. MyScriptableObject myScriptableObject = ScriptableObject.CreateInstance<MyScriptableObject>();
    2. JsonUtility.FromJsonOverwrite(json, myScriptableObject);
     
    Bunny83 likes this.