Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unity Deserialize Into Scriptable Object

Does anyone know why this code below will return the error

ArgumentException: Cannot deserialize JSON to new instances of type 'CatalogueList.'
UnityEngine.JsonUtility.FromJson[CatalogueList]

My Catalogue list lives in my assets and i can serialize and upload to my server perfectly fine, im trying to download my file and fill in all fields with the json.

Here is the code.

void AddDownloadedItems(string text, CatalogueList list)
{
    CatalogueList inventoryItemList = UnityEditor.AssetDatabase.LoadAssetAtPath("Assets/CatalogueItem.asset", typeof(CatalogueList)) as CatalogueList;
    list = JsonUtility.FromJson<CatalogueList>(text);
}

But as i say it will just return the error?

CatalogueItemList Code

public class CatalogueList : ScriptableObject { 
    public List<CatalogueItem> itemList;
}

Catalogue Item Code

[System.Serializable]                                                           //  Our Representation of an InventoryItem
public class CatalogueItem
{
    public string databaseID;
    public string itemName = "New Item";
    public enum PrizeMachine { Bronze, Silver, Gold, Platinum };
    public PrizeMachine myMachine;                     
    public Texture2D itemThumb = null;
    public Texture2D itemIcon = null;
    public string itemThumbName;
    public string itemIconName;
    public string shortDescripion;
    public string fullDescription;                                 
    public int priceInBronze;
    public int priceInSilver;
    public int priceInGold;
    public int priceInPlatinum;
}
like image 805
John Esslemont Avatar asked Oct 12 '25 19:10

John Esslemont


1 Answers

Use FromJsonOverwrite instead!

Note that the JSON Serializer API supports MonoBehaviour and ScriptableObject subclasses as well as plain structs/classes. However, when deserializing JSON into subclasses of MonoBehaviour or ScriptableObject, you must use FromJsonOverwrite; FromJson is not supported and will throw an exception.

https://docs.unity3d.com/2022.3/Documentation/ScriptReference/JsonUtility.FromJsonOverwrite.html

So for you that'd be

JsonUtility.FromJsonOverwrite(text, list);

Note that this is not an immutable method and will overwrite your object, but it seems like that was your intention anyway.

like image 137
Fredrik Schön Avatar answered Oct 16 '25 08:10

Fredrik Schön