JSON to Scriptable object

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.

Yes!

Steps to success:

  • iterate your JSONs

  • for each SO, create the SO yourself with ScriptableObject.CreateInstance();

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

Aiiight!
I was missing the AssetDatabase
Worked like a charm!
Thanks

1 Like

I don’t know how populate works in Newtonsoft, but if you are using Unity’s Json deserializer, It might be worth mentioning:

MyScriptableObject myScriptableObject = ScriptableObject.CreateInstance<MyScriptableObject>();
JsonUtility.FromJsonOverwrite(json, myScriptableObject);
3 Likes

I encountered a similar issue with storing data in a ScriptableObject (SO) and trying to read/write it to/from JSON using JsonUtility.FromJson<>(), which did not work for ScriptableObjects. However, creating a new instance and using JsonUtility.FromJsonOverwrite(json, SO) solved the problem perfectly.

1 Like