How can i extract “ ” “from json register in java

Tags: ,



I’m working with a java’s library (Gson) to store new Users in a file named “users.json). When i register a new one, my code reads previous data in the file to convert and add with the new data in a List of Users to write the new content to the json file. The problem comes when the previous data are readed, because it’s stored like the next example:

[
  {
    "name": "First",
    "second_name": "User",
    "age": "27",
    "email": "data1email@email.com",
    "user_id": "UtPdadq",
    "password": "email1Password123"
  }
]

and with new data:

[
  {
    "name": ""First"",
    "second_name": ""User"",
    "age": ""27"",
    "email": ""data1email@email.com"",
    "user_id": ""UtPdadq"",
    "password": ""email1Password123""
  },
  {
    "name": "Second",
    "second_name": "User",
    "age": "28",
    "email": "data2email@email.com",
    "user_id": "ehOFXzI",
    "password": "email2Password123"
  }
]

I’ll give you the User class and the main function for more information

public class User {
    //user's variables
    String name;
    String second_name;
    String age;
    String email;
    String user_id; //automatically generated
    String password;


    //constructor without parameters
    public User(String nameUser, String second_name_user, String ageUser, String emailUser, String passwordUser) {}
    //coonstructor with parameters
    public User(String name, String second_name, String age, String email, String user_id, String password) {
        this.name = name;
        this.second_name = second_name;
        this.age = age;
        this.email = email;
        this.user_id = user_id;
        this.password = password;
    }

    public User() {

    }


    //Setters and getters
}

and the main

public static void signUp(String filename) {// add user
        System.out.println("Please, remember that you should restart this app when you are registered.");
        User new_user = new User();//new user's instance
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter data: ");
        System.out.println("==================");
        String id = generateUserId() ;
        System.out.println("Enter your email: ");
        String emailUser = scanner.nextLine();
        System.out.println("Enter your password: ");
        String passwordUser = ingressPassword();
        System.out.println("Enter your name: ");
        String nameUser = scanner.nextLine();
        System.out.println("Enter your second name: ");
        String second_name_User = scanner.nextLine();
        System.out.println("Enter your age: ");
        String ageUser = scanner.nextLine();

        new_user.setUser_id(id);
        new_user.setEmail(emailUser);
        new_user.setPassword(passwordUser);
        new_user.setName(nameUser);
        new_user.setSecond_name(second_name_User);
        new_user.setAge(ageUser);

        //Test
        //System.out.println(new_user.getClass());
        try
        {
            //new file instance at the path
            File file = new File(filename);
            //tries to create new file in the system
            boolean bool=file.createNewFile();
            Path path = Paths.get(filename);

            List< User > users = new ArrayList< >();


            if(bool){
                users.add(new_user);
                try (Writer writer = Files.newBufferedWriter(path, StandardCharsets.UTF_8)) {
                    Gson gson = new GsonBuilder().setPrettyPrinting().create();

                    JsonElement tree = gson.toJsonTree(users);
                    gson.toJson(tree, writer);
                }

                System.out.println("Users written to file");

            }else {
                try (Reader reader = Files.newBufferedReader(path,
                        StandardCharsets.UTF_8)) {
                    JsonObject car=null;
                    JsonParser parser = new JsonParser();
                    JsonElement tree = parser.parse(reader);

                    JsonArray array = tree.getAsJsonArray();

                    for (JsonElement element: array) {
                        if (element.isJsonObject()) {
                            car = element.getAsJsonObject();
                        }
                    }

                    String idPrev = car.get("user_id").toString();
                    String emailPrev = car.get("email").toString();
                    String passPrev = car.get("password").toString();
                    String namePrev = car.get("name").toString();
                    String snamePrev = car.get("second_name").toString();
                    String agePrev = car.get("age").toString();

                    //System.out.println(idPrev);
                    //add data to list
                    User userPrev = new User();

                    userPrev.setUser_id(idPrev);
                    System.out.println(userPrev.getUser_id());
                    userPrev.setEmail(emailPrev);
                    userPrev.setPassword(passPrev);
                    userPrev.setName(namePrev);
                    userPrev.setSecond_name(snamePrev);
                    userPrev.setAge(agePrev);

                    //two objects User: userPrev and new_user
                    System.out.println("*******************");
                    System.out.println(userPrev);
                    System.out.println("*******************");
                    System.out.println(new_user);
                    System.out.println("*******************");

                   //add User objects to the same List
                    users.add(userPrev);
                    users.add(new_user);

                    //json
                    try (Writer writer = Files.newBufferedWriter(path, StandardCharsets.UTF_8)) {
                        Gson gson = new GsonBuilder().setPrettyPrinting().create();

                        JsonElement tree2 = gson.toJsonTree(users);
                        gson.toJson(tree2, writer);//write
                    }

                    System.out.println("Users written to file");
                }
            }
        }catch (IOException e){e.printStackTrace();}
    }

Answer

There are 2 problems with your code.

  1. You are reading just the previous object from file and overwriting the older objects. Which means the file will always have the last 2 objects and not older. (Unless this is what you intended.)
  2. You are manually reading the json file and setting each attribute in user object. You should let Gson do this for you.

So, delete following code

                    JsonObject car=null;
                    JsonParser parser = new JsonParser();
                    JsonElement tree = parser.parse(reader);

                    JsonArray array = tree.getAsJsonArray();

                    for (JsonElement element: array) {
                        if (element.isJsonObject()) {
                            car = element.getAsJsonObject();
                        }
                    }

                    String idPrev = car.get("user_id").toString();
                    String emailPrev = car.get("email").toString();
                    String passPrev = car.get("password").toString();
                    String namePrev = car.get("name").toString();
                    String snamePrev = car.get("second_name").toString();
                    String agePrev = car.get("age").toString();

                    //System.out.println(idPrev);
                    //add data to list
                    User userPrev = new User();

                    userPrev.setUser_id(idPrev);
                    System.out.println(userPrev.getUser_id());
                    userPrev.setEmail(emailPrev);
                    userPrev.setPassword(passPrev);
                    userPrev.setName(namePrev);
                    userPrev.setSecond_name(snamePrev);
                    userPrev.setAge(agePrev);

                    //two objects User: userPrev and new_user
                    System.out.println("*******************");
                    System.out.println(userPrev);
                    System.out.println("*******************");
                    System.out.println(new_user);
                    System.out.println("*******************");

                   //add User objects to the same List
                    users.add(userPrev);

and replace with single line

users = new Gson().fromJson(reader, new TypeToken<List<User>>(){}.getType());

Here is the complete code

public class GsonWriteToFile {

    public static void main(String[] args) {
        signUp("gson-file.txt");
    }

    public static void signUp(String filename) {// add user
        System.out.println("Please, remember that you should restart this app when you are registered.");
        User new_user = new User();//new user's instance
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter data: ");
        System.out.println("==================");
        String id = "randomId";// Use generateUserId() ; here
        System.out.println("Enter your email: ");
        String emailUser = scanner.nextLine();
        System.out.println("Enter your password: ");
        String passwordUser = scanner.nextLine();// use ingressPassword(); here
        System.out.println("Enter your name: ");
        String nameUser = scanner.nextLine();
        System.out.println("Enter your second name: ");
        String second_name_User = scanner.nextLine();
        System.out.println("Enter your age: ");
        String ageUser = scanner.nextLine();

        new_user.setUser_id(id);
        new_user.setEmail(emailUser);
        new_user.setPassword(passwordUser);
        new_user.setName(nameUser);
        new_user.setSecond_name(second_name_User);
        new_user.setAge(ageUser);

        //Test
        //System.out.println(new_user.getClass());
        try {
            //new file instance at the path
            File file = new File(filename);
            //tries to create new file in the system
            boolean bool = file.createNewFile();
            Path path = Paths.get(filename);

            List<User> users = new ArrayList<>();


            if (bool) {
                users.add(new_user);
                try (Writer writer = Files.newBufferedWriter(path, StandardCharsets.UTF_8)) {
                    Gson gson = new GsonBuilder().setPrettyPrinting().create();

                    JsonElement tree = gson.toJsonTree(users);
                    gson.toJson(tree, writer);
                }

                System.out.println("Users written to file");

            } else {
                try (Reader reader = Files.newBufferedReader(path,
                        StandardCharsets.UTF_8)) {
                    // change starts
                    users = new Gson().fromJson(reader, new TypeToken<List<User>>(){}.getType());
                   // change ends
                    users.add(new_user);

                    //json
                    try (Writer writer = Files.newBufferedWriter(path, StandardCharsets.UTF_8)) {
                        Gson gson = new GsonBuilder().setPrettyPrinting().create();

                        JsonElement tree2 = gson.toJsonTree(users);
                        gson.toJson(tree2, writer);//write
                    }

                    System.out.println("Users written to file");
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}


Source: stackoverflow