Skip to content

Instantly share code, notes, and snippets.

@renepanke
Last active June 1, 2021 20:27
Show Gist options
  • Save renepanke/aa744a7b32a24eeed1ce1d007d5e52b3 to your computer and use it in GitHub Desktop.
Save renepanke/aa744a7b32a24eeed1ce1d007d5e52b3 to your computer and use it in GitHub Desktop.
How to create an easy JSON based configuration class

How to create an easy JSON based configuration class

Credits for this Gist go to frankred/json-config-file.

1. Dependencies

To create a json based config you can easily use the following maven dependency:

<dependency>
  <groupId>com.google.code.gson</groupId>
  <artifactId>gson</artifactId>
  <version>2.8.6</version>
</dependency>

2. Implementation

  1. Create a new class for example Config.

  2. Add public member variables like you would do in any other class.

  3. In case you want to set any default values to be loaded when the configuration file is missing, add a method setDefaults() where you set those values. Call this method in the constructor of the Config class.

  4. Paste the following code into your class:

private static Config instance;

	public static Config getInstance() {
		if (instance == null) {
			instance = fromDefaults();
		}
		return instance;
	}

	public static void load(File file) {
		instance = fromFile(file);

		// no config file found
		if (instance == null) {
			instance = fromDefaults();
		}
	}

	public static void load(String file) {
		load(new File(file));
	}

	private static Config fromDefaults() {
		Config config = new Config();
		return config;
	}

	public void toFile(String file) {
		toFile(new File(file));
	}

	public void toFile(File file) {
		Gson gson = new GsonBuilder().setPrettyPrinting().create();
		String jsonConfig = gson.toJson(this);
		FileWriter writer;
		try {
			writer = new FileWriter(file);
			writer.write(jsonConfig);
			writer.flush();
			writer.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private static Config fromFile(File configFile) {
		try {
			Gson gson = new GsonBuilder().setPrettyPrinting().create();
			BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(configFile)));
			return gson.fromJson(reader, Config.class);
		} catch (FileNotFoundException e) {
			return null;
		}
	}

	@Override
	public String toString() {
		Gson gson = new GsonBuilder().setPrettyPrinting().create();
		return gson.toJson(this);
	}

Now you're able to call the methods save(String file) and save(File file) to save your configuration to a file.

Loading works with calling the methods load(String file) or load(File file). After loading the member variables will be set.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment