Reading/Writing JSON Constantly

Hello Guys, im back from a long needed break from programming and I’m back with another question.

I’ve never had to approach json in java before and I had to get an external library to get everything working properly. So bear with me for a moment.

I’m trying to make the json file of the player basically a “database” for the player. Something I can reference from other classes using methods I have built. Etc. This is the code that I have currently WORKING, but something does not feel right. I feel like there is a terrible problem with the implementation of the code. Can someone tell me how they would do theirs? Maybe some advice? Thanks.

package com.rojarstudios.prisma.saveSystem;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input.Keys;

public class SaveSystem {
	
	JSONObject obj = new JSONObject();
	ReadData read = new ReadData();
	
	File playerData = new File("assets/data/player.json");
	
	private boolean levelUp = false;

	public SaveSystem() {

	}
	
	public void Ding(){
		levelUp = true;
	}
	
	public void DataManager(String file) throws IOException{
		// Call all the needed methods that make changes to the json file.
		PlayerDefaultFile();
		changeLevel();
		changePlayerHP();
		// Then use the collected obj refrences to write to the file.
		writePlayerData(file);
		if (Gdx.input.isKeyPressed(Keys.SPACE)) {
			Ding();
		}
	}
	
	@SuppressWarnings("unchecked")
	public void changeLevel() {
		if (levelUp) {
			obj.put("level", (read.readData("assets/data/player.json", "level") + 1));
			levelUp = false;
		}
	}
	
	@SuppressWarnings("unchecked")
	public void changePlayerHP() {
		if ((read.readData("assets/data/player.json", "player_hp")) > 0) {
			obj.put("player_hp", read.readData("assets/data/player.json", "player_hp") - 30);
		}
	}

	public void writePlayerData(String fileName) throws IOException{
		try {
			// Make sure the file gets written to the right dir.
			FileWriter file = new FileWriter(fileName);
			if(playerData.exists()) {
				file.write(obj.toJSONString());
				file.flush();
				file.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	@SuppressWarnings("unchecked")
	public void PlayerDefaultFile() throws IOException{
		if (!playerData.exists()) {

			obj.put("name", "ROJAR");
			obj.put("level", 1);
			obj.put("player_hp", 100);
			obj.put("player_mana", 100);
			obj.put("player_stamina", 100);
			obj.put("player_x", 50);
			obj.put("player_y", 50);
		 
			// We can store the current items of the player in a list.
			// Use the item ID's.
			JSONArray inventory = new JSONArray();
			inventory.add("001");
			inventory.add("069");
			inventory.add("333");
		 
			obj.put("items", inventory);
		} else {
			// Do nothing. Player.json already created.
		}
	}

}

Oh, and basically all readData(); does is readData(file, property); just grabs the json property I want from the file I specified.

I don’t really understand your problem, but from what I know, I would only use json for saving data to hard drive or sending json in networking. Using json inside the application so the application itself can access data as json seems silly to me…

[quote=“Atheistzilla,post:1,topic:47963”]
Your problem description is supremely vague: “I feel like there is a terrible problem” ;D Can you be more specific, e.g. what are you trying to achieve and what does not work?

And I have no clue what you are trying to do. You do know that you can acccess (public) data in other classes without having to save it to disk first, right? Since disk access is many, many magnitudes slower than memory access that would be the obvious solution.

Don’t save all the time to disk, when you change a value. It doesn’t cost much to save a smal json file once, but if you save it every time you update a value you will run into problems sooner or later. Store your values in a class (or multiple classes) and find on which occasions in your game you should save.

I am to persisting my game state to json, but I only do it at certain points in the game (when starting a level, when watching a sequence or when quitting the game or exiting to the main menu etc.).

Sorry guys, I was meaning to say if my code is clunky. Because it feels clunky and I, personally feel like im doing it wrong and want to learn the right way to do it.

Im just trying to save my needed player data into a JSON. ;D

Last night I also agreed to not save data constantly. Im just going to do a “Save and Exit” kind of deal, just writing once, but shouldnt I really use JSON? Will thrre be performance issues later on using this over XML or CSV or something?

There’s an old saying about premature optimization. If JSON is working for you, then stick with it. If you’ve structured your code correctly, then all access to the JSON functionality should be abstracted through your SaveSystem class. If JSON stops being a good fit for your game down the road, you’re free to change the internal implementation of SaveSystem to another technology with minimal (if any) impact on the other classes in your game. :point:

I think this is the right mindset :wink:

What I like to do to do is to make my data objects themselves implement the libgdx Serializable interface. The serialization code is then located with the object instead of some other code file.

Here is an example of a class in my project.

http://pastebin.com/k13G0EHX

At the bottom are two methods to read from or write to a file. Normally I have the loading and saving code located somewhere else, but I put it here so I just have to post one file :wink:

[Edit]
Ah sorry, I think I just see know what you are asking exactly. Take my file as example. Better make a class like that where you store your data, like hp etc. When you save, you simply save this class via serialization. You can instance this class in your main code and store it as a field or variable where you need it (or where you need it) instead of accessing the file directly. When you load a game, you can simply read the file via the json object and have your object ready.
[/Edit]