- Home /
Other
How to save and load any data type?
Hello, I have seen this somewhere in games where you can save and load any type of data instead of creating separate ones for each class. For example I have a Save() function:
public static void Save(someclass)
{
I want to get the "someclass" data and save it to a json file.
}
public static (someclass return) Load(file)
{
Load the "file" then read it and return the "someclass".
}
So how do I do something like this?
Thank you.
Answer by sacredgeometry · Aug 11, 2019 at 05:32 PM
The industry standard JSON serialiser for c# is Newtonsoft.JSON, the frameworks file writing classes are in the IO namespace.
Example
public T ReadFileAs<T>(string path) {
var json = File.ReadAllText(path)
return JsonConvert.DeserializeObject<T>(json);
}
public void SaveFile(string path, Object obj) {
var json = JsonConvert.SerializeObject(obj, Formatting.Indented);
File.WriteAllText(path, json);
}
So the steps are:
For saving
Serialise Object to json string
Persist String to txt file
For reading saved file:
Load File and get string from it
Deserialise string to object
There isnt really much to it.
https://www.newtonsoft.com/json/help/html/SerializingJSON.htm
and
https://stackoverflow.com/questions/7569904/easiest-way-to-read-from-and-write-to-files
or
The question is how to save and load any type of data which I could of provided more information on what I really want.
Anyways I have found it to be something like this:
public static void Save<T>(string fileName, object obj)
{
}
public static T Load<T>(string fileName)
{
}
Hopefully this is the right methods however you might know if this is the way of doing this?
I thought you wanted to know how to actually do it not how to format generic methods.
Either way. thats not entirely necessary for the method I explained.
Question was kinda misleading as I already know and have used JSON few times. Thanks anyways for your time.
Follow this Question
Related Questions
Loading a list into unity 0 Answers
Saving GameObject to file 2 Answers
Saving/Loading data to Windows Phone 8 3 Answers
How can I save and load a player's position? 5 Answers
SimpleJSON array problem 0 Answers