Creating/Reading JSON Objects

Help Needed!

I am a young programmer (like, really young), and am trying to not use my usual java.io.File imports and instead use JSON Simple, or something else of the sort. I need a guide or at least a start to doing really anything in JSON, as I am new to the whole sort. I don’t need just JSON Simple, it can be other stuff like GSON, Jackson, etc. The only thing I do want is for the object to be neat inside the contents of a file. Thanks!

TheNewJavaman/GStuff

Edit: Can someone please give me some help of how to create, manage, and read any type or JSON? I am so confused :frowning:

GSON is one of the simplest to get started with as you can simply serialise/deserialise a POJO. This can be your own object or nested hash maps or whatever. To use it you simply create an instance of Gson and use toJson and fromJson to convert from your object to JSON and vice versa.

Here is an example of a class which can read and write itself to JSON using Gson

1 Like

Thank you so much!
So the .setPrettyPrinting() makes it look good in a file, or no?

Erm… I don’t get the code now that I try to understand it better. Can you help me out again a bit, please?

Just post your code.

Example from file

File jsonFile = ...;
Gson gson = new Gson();
MyPojoClass bean = gson.fromJson(new FileReader(jsonFile), MyPojoClass.class);

Example from string

String jsonString = ...;
Gson gson = new Gson();
MyPojoClass bean = gson.fromJson(jsonString, MyPojoClass.class);

Example to file

File jsonFile = ...;
MyPojoClass bean = ...;
Gson gson = new Gson();
gson.toJson(bean, jsonFile);

Example to file with pretty printing

File jsonFile = ...;
MyPojoClass bean = ...;
Gson gson = new GsonBuilder().setPrettyPrinting().create();
gson.toJson(bean, jsonFile);

See also Gson Documentation on GitHub

Okay, I think that I get it. I’m testing out a couple different things that I’ve seen online as well. Thank you all so much!

The AFK file is just for me to test it as a command. Scroll down to see my methods for making a file. I have an error, and in the stacktrace, it tells me that FileMethods.java is doing something wrong.

package net.javaman.afkpro;

import java.io.IOException;

import org.spongepowered.api.command.CommandException;
import org.spongepowered.api.command.CommandResult;
import org.spongepowered.api.command.CommandSource;
import org.spongepowered.api.command.args.CommandContext;
import org.spongepowered.api.command.spec.CommandExecutor;
import org.spongepowered.api.entity.living.player.Player;
import org.spongepowered.api.text.Text;

import com.google.gson.JsonObject;

import net.javaman.filemethods.FileMethods;

public class Afk implements CommandExecutor {
    @Override
    public CommandResult execute(CommandSource src, CommandContext args) throws  CommandException {
	Player p = (Player) src;
	String player = p.getName();
	String uuid = p.getUniqueId().toString();

	if (src instanceof Player) {
		JsonObject json = new JsonObject();
		json.addProperty("player", player);
		json.addProperty("uuid", uuid);
		Main.getLogger().info("Look -----> " + json.toString());
		try {
			FileMethods.create("config/afkpro", "json.txt", null);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	} else {
		src.sendMessage(Text.of("You cannot send this command!"));
	}
	return CommandResult.success();
    }
}

And now for FileMethods.java:

package net.javaman.filemethods;

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

import net.javaman.afkpro.Main;

public class FileMethods {
    public static void create(String path, String name, String text) throws IOException {
	File dir = new File(path);
	dir.mkdirs();
	FileWriter file = new FileWriter(path + "/" + name);
	file.write(text);
	file.flush();
	file.close();
    }
}

What is the stack trace?

Why are you passing null to your create method? Also your use of filewriter is not using the dir variable. I would suggest revising to:

FileWriter file = new FileWriter(new File(dir, name));

However I don’t recommend writing your own FileMethods class anyway. Just use guava:

File dir = new File(path);
File file = new File(dir, name);
Files.write(string.getBytes(Charsets.UTF_8), file);

or java nio:

Files.write(Paths.get(path, name), string.getBytes(Charsets.UTF_8))

or apache commons:

File dir = new File(path);
File file = new File(dir, name);
FileUtils.writeStringToFile(file, string, "UTF-8");

These tools will help to validate and analyze JSON data.

JSON Formatter
JSON Validator