1

It keeps printing "unsuccessful login" even though the json file it is reading from actually contains {"beansly":"beans"} on the first line and the only line.

Is there any way to have gson parse the key value pair and return the value of the key "beansly"?

in login()

private static void login(String username, String password) throws IOException {
        JsonElement jsonData = readOrCreateNew(new File(".\\data.json")).get(username);
        String passwordData = new Gson().fromJson(jsonData, String.class);
        if (passwordData == password) {
            System.out.println("Login successful");
        }
        else if (passwordData != password) {
            System.out.println("Login unsuccessful");
        }
    }

in readOrCreateNew()

private static JsonObject readOrCreateNew(File f) throws IOException {
        Gson gson = new Gson();
        if (f.exists() && f.length() > 0) {
            // Using "try" with parentheses to automatically close the BufferedReader
            try (BufferedReader reader = new BufferedReader(new FileReader(f))) {
                return gson.fromJson(reader, JsonObject.class);
            }
        }
        return new JsonObject();
    }
  • 2
    You probably should use if(password.equals(passwordData)) and don't use == See for instance https://stackoverflow.com/questions/7520432/what-is-the-difference-between-and-equals-in-java – R.Groote Nov 22 '19 at 06:44
  • @R.Groote Thanks for the suggestion! Still keeps giving me "Login unsuccessful" though. –  Nov 22 '19 at 06:52

1 Answers1

0

When you have JsonElement you do not need to convert it to String using Gson. Just get String by calling getAsString():

String passwordData = jsonData.getAsString();
if (passwordData.equals(password)) {
    System.out.println("Login successful");
} else {
    System.out.println("Login unsuccessful");
}
Michał Ziober
  • 37,175
  • 18
  • 99
  • 146
  • 1
    Thank you so much, finally my program is complete, i'll also remember what you have taught me so far! Thanks again :) –  Nov 22 '19 at 08:06