1

What is the best way to delete an item from a JSON file using Unity 3d's JsonUtility?

I'm assuming you must load it, but: does it need to be parsed or converted to a list?

Once the operation is done, save it. Any help for the middle part would be helpful. Thanks!

Ken Gordon
  • 195
  • 6
  • 20

1 Answers1

1

I'm assuming you must load it, but: does it need to be parsed or converted to a list?

Yes, with JsonUtility you must load it, convert it to List then remove the item from it. First of all, the item must have a variable you can use to identify and remove it. Let's say that the name of the item to delete is "ken";

Test data to load serialize and de-serialize:

[Serializable]
public class PlayerData
{
    public string name;
    public int score;
}

Load(Must be loaded as array then converted back to List):

string jsonToLoad = PlayerPrefs.GetString("Data");
//Load as Array
PlayerData[] _tempLoadListData = JsonHelper.FromJson<PlayerData>(jsonToLoad);
//Convert to List
List<PlayerData> loadListData = _tempLoadListData.OfType<PlayerData>().ToList();

Remove all "ken" Items:

for (int i = 0; i < loadListData.Count; i++)
{
    if (loadListData[i].name == "ken")
    {
        loadListData.Remove(loadListData[i]);
    }
}

or with Linq:

loadListData.RemoveAll((x) => x.name == "ken");

Then you can save it:

string jsonToSave = JsonHelper.ToJson(loadListData.ToArray());
PlayerPrefs.SetString("Data", jsonToSave);
PlayerPrefs.Save();

Of-course, you will need JsonHelper as mentioned in your other post.

Programmer
  • 121,791
  • 22
  • 236
  • 328