简体   繁体   中英

Best way to delete an item from a JSON string using JsonUtility in Unity 3d

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!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM