How can I check if a json file exists, and if not create one? And then how can I load this list, and save it when I need to? I’ve read up on JSON Utility but can’t figure out how to get a list to save and load correctly.
Also, on topic, I know json utility works with Lists, but how does it handle serializing derived classes? For example, using the code above, if I had a public class SomeClass, and then a public class OtherClass : SomeClass and the list above contained both of these.
Use File.Exists(…) to check if a file already exists. If you wish to write a Json file, you’d do something like this:
var class = new MyList();
var outputString = JsonUtility.ToJson(class);
File.WriteAllText(“C:\MyFile.json”, outputString);
In reverse, you can deserialize anything doing this:
var inputString = File.ReadAllText(“C:\MyFile.json”); var class = JsonUtility.FromJson<MyList>(inputString);
Oh, and on the topic of derived classes: you might as well just try it out for yourself, but if something’s public in a root type, it’s still public in the derived class and JsonUtility will be able to read/write from it.
Thank you very much for your reply. Very concise! I will try this when I get home.
On the topic of derived classes, what I meant was; normally to populate my list I would do:
Add (new SomeClass(constructor variables here));
Or:
Add (new OtherClass (constructor variables here));
I know unity’s serializer struggles to deserialize derived classes, and they deserialize as the parent class type. Do you still have this problem using JSON UTILITY?
I work with deserialization a lot, but I can’t say I have been working with the JsonUtility and deserialization of derived types that much. Maybe it’s a good idea to create a demo project which tests only that. I’d try it for you right now, but I’ve got some other bugfixing to do
Okay so I got this working, however I was right about the derived class issue. Going to try and derive from ScriptableObject and see if this fixes the issue
Seems weird that you wouldn’t be able to. In the message you made before you edited it you should try to make a wrapping class containing the array, and (de)serializing that instead.
[System.Serializable]
public class WrappingClass {
public List<Item> Inventory;
}
var variable = new WrappingClass() { Inventory = someOtherList };
JsonUtility.ToJson(variable);
I’m not too sure about JsonUtility being able to directly convert a list or array to a generic Json array.
Hiya, hey I’ve been using this quite a bit for saving and loading through json, it’s really handy.
Just wondering, is there a way to make the list generic? It’s just that I’ve ended up with a bunch of different wrapping classes for different types and It would be nice to just have one generic one.