1

Currently using LitJson in my development. Json is working perfectly fine in Unity Editor but not in android device. Tried various ways in loading the json file but nothing worked. Here is my latest code:

string path = Application.persistentDataPath + "/Products.json";
    string jsonString = File.ReadAllText (path);
    if(File.Exists(path)) {
    jsonParser data = JsonUtility.FromJson<jsonParser>(jsonString);

    data.products.Add (product);
    Debug.Log (data.products [1].code);

    string jsonString2 = JsonUtility.ToJson (data);
    Debug.Log (jsonString2);

    File.WriteAllText (path, jsonString2.ToString());
    } else{
        File.WriteAllText (path, jsonString);
    }

Big thanks!

Sarah
  • 135
  • 3
  • 19

1 Answers1

-1

I suggest you using Resources loading instead of IO since the least is something platform specific. So if you create a "Resources" folder in the root of Assets folder of your project and put your json file in it so it looks like this "/Assets/Resources/Products.json" and change you code to this

    string jsonString = Resources.Load<string>("Products.json");
    if (jsonString != null)
    {
        jsonParser data = JsonUtility.FromJson<jsonParser>(jsonString);

        data.products.Add(product);
        Debug.Log(data.products[1].code);

        jsonString = JsonUtility.ToJson(data);
        Debug.Log(jsonString);
    }
    using (FileStream fs = new FileStream("Products.json", FileMode.Create))
    {
        using (StreamWriter writer = new StreamWriter(fs))
        {
            writer.Write(jsonString);
        }
    }
    UnityEditor.AssetDatabase.Refresh();

everything should work fine.