- Home /
Modifying Json file values
I am making a simple character customization element for my game, and I made a Json database for the items.
[ { "id": 1, "name": "hat", "key": "Hat01", "price": 10, "available": false }, { "id": 2, "name": "hat2", "key": "Hat02", "price": 80, "available": false },
I can pull out the data and put it into a shop screen, but when the player buys an item, I would like to change the "available" variable to be true and save it so everytime I pull information from Json, that hat is available. How can I achieve this? Something to overwrite just one line of the Json file.
Thank you in advance.
Answer by dvandamme · Mar 30, 2017 at 02:44 AM
you dont edit json files. you store data as json, and then read it into data structures. if youre trying to edit a json file then stop. Javascript object notation is for storage and transfer, not manipulation when in a proper OO environment. maybe web coders do that, but full OO coding should deserialize a JSON string into a data structure for manipulation.
when you've made a data structure that holds that object, then its easy. which I'll assume is called dataset and represents a list holding stockItem
then you could do something like
// assuming you have access to use System.Linq for the funky list and find; becusae, you should, its great
List <stockItem> stock = new List<stockItem>();
// deserialize your json into that list and then manipulate
stockItem item = stock.find(x => x.id == "1");
item.available = false;
and then serialize that back to a file
Answer by funki · Apr 01, 2017 at 04:11 PM
Thank you, I figured it out, I replaced the whole json text instead of only one line, thus updating the information. Here is the code for anyone interested:
string json;
json = ("[");
for (int i = 0; i < itemData.Count; i++)
{
NewitemData = JsonMapper.ToJson(itemData[i]);
if(i== itemData.Count-1)
{
json = (json + NewitemData.ToString());
}
else
{
json = (json + NewitemData.ToString()+ ",");
}
}
json = (json + "]");
File.WriteAllText(Application.dataPath + "/Resources/Items.json", json);
This works if you want to turn lists into json format.
Your answer
Follow this Question
Related Questions
Anyone having experience with Firebase? 0 Answers
Converting from SQLite Database to JSON 2 Answers
Scriptable Objects as a datatable 1 Answer
LitJson not working correctly 2 Answers
Unity doesn't see files inside StreamingAssets folder 1 Answer