- Home /
How to save and load a json file on android
Hello I'm making an android game but the game wont load save files which is a json file some people say that i use resource.load but thats only for read only files and Ii'm trying to load a save file.
Can someone please help with the code for proper json file saving and loading I've also used File.Readalltext and File.Writealltext but cant read the json file
Someone please help
Answer by WinterboltGames · Oct 30, 2017 at 08:36 AM
here's a code snippet:
using UnityEngine;
using System.IO;
public class JsonFileWriter : MonoBehaviour
{
public JsonData data;
public string path;
public void Start ()
{
data = new JsonData(1, "Alfred Jodl");
path = Path.Combine(Application.persistantDataPath, "saved files", "data.json");
SerializeData();
DeserializeData();
}
public void SerializeData ()
{
string jsonDataString = JsonUtility.ToJson(data, true);
File.WriteAllText(path, jsonDataString);
Debug.Log(jsonDataString);
}
public void DeserializeData ()
{
string loadedJsonDataString = File.ReadAllText(path);
data = JsonUtility.FromJson<JsonData>(loadedJsonDataString);
Debug.Log("id: " + data.id.ToString() + " | name: " + data.name)
}
}
[Serializeable]
public class JsonData
{
public int id;
public string name;
public JsonData (int id, string name)
{
this.id = id;
this.name = name;
}
public JsonData (){}
}
No overload method 'Combine' takes 3 arguments
Application.persistantDataPath how to do you create a save file with 'N - coins' at the start?
That Path.Combine(Application.persistantDataPath, "saved files", "data.json");
is just the same as Application.persistantDataPath + "/saved files" + "/data.json" on PC. But it could be useful if your system are using "\" ins$$anonymous$$d of "/".
That data.json is (save filename).(format extension), so if you want to create something like "N - coins.json" you could simply just replace the "data" to your 'N - coins'.
Your answer
Follow this Question
Related Questions
Windows Phone 8.1 WWW post request error 0 Answers
Unity can read Json file, but Android not. 2 Answers
LitJSON android problem 1 Answer
How to do communication between apps. ( Android ) 2 Answers
Unity project on android - OnPointerDown/Up movement 1 Answer