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
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.
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();
}
}