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


    Dec 30, 2014
    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


    Mar 16, 2013

    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).

    Also, always be sure to leverage sites like:

    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


    Dec 30, 2014
    I was missing the AssetDatabase
    Worked like a charm!
    Kurt-Dekker likes this.
  4. Blenderik


    May 14, 2013
    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.