-3

I need to serialize java objects for one of my uni projects, but I don't have much experience in java. I was wondering why toJson keeps returning an empty object when I try to print it and why it doesn't write anything in the file.

Here's my code

import java.util.*;
import java.util.stream.Collectors;
import java.io.*;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class UniShop {

    private static User currentUser;
    private static ArrayList<Buyer> buyers;
    public static List<Product> products;
    public static ArrayList<Order> orders;
    private static ArrayList<Reseller> resellers;

    public UniShop() {
        buyers = new ArrayList<>();
        products = new ArrayList<>();
        orders = new ArrayList<>();
        resellers = new ArrayList<>();
    }

    public static void addBuyer(Buyer buyer) {
        buyers.add(buyer);
    }

    public static void addReseller(Reseller reseller) {
        resellers.add(reseller);
    }

    public static void placeOrder(Order order) {
        orders.add(order);
    }

    public void confirmArrival(Product product) {
        // TODO: Confirming arrival of a product
    }

    public void Payment(Order order) {
        // TODO: Select order payment type, validate payment, etc...
    }

    private static User findUserByUID(String uid) {
        for (Buyer buyer : buyers) {
            if (buyer.getUid().equals(uid)) {
                return buyer;
            }
        }

        for (Reseller reseller : resellers) {
            if (reseller.getUid().equals(uid)) {
                return reseller;
            }
        }

        return null; // User not found
    }

    public static void followUser() {
        Scanner scanner = new Scanner(System.in);

        System.out.println("Follow/Like User Menu:");
        System.out.println("[1] Follow a Buyer");
        System.out.println("[2] Like a Reseller");
        System.out.println("[3] Go Back");
        System.out.print("Enter your choice: ");

        int choice = scanner.nextInt();
        scanner.nextLine(); // Consume the newline character

        switch (choice) {
            case 1:
                followBuyer(scanner);
                break;

            case 2:
                followReseller(scanner);
                break;

            case 3:
                // Go back to the main menu
                break;

            default:
                System.out.println("Invalid choice. Please enter a valid option.");
        }
    }

    // Follow a buyer based on UID
    private static void followBuyer(Scanner scanner) {
        System.out.print("Enter the UID of the buyer you want to follow: ");
        String uid = scanner.nextLine();

        Buyer buyerToFollow = (Buyer) findUserByUID(uid);

        if (buyerToFollow != null) {
            currentUser.followBuyer(buyerToFollow);
            System.out.println("You are now following the buyer: " + buyerToFollow.getFullName());
        } else {
            System.out.println("Buyer with UID " + uid + " not found.");
        }
    }

    // Follow a reseller based on UID
    private static void followReseller(Scanner scanner) {
        System.out.print("Enter the UID of the reseller you want to 'like': ");
        String uid = scanner.nextLine();

        Reseller resellerToFollow = (Reseller) findUserByUID(uid);

        if (resellerToFollow != null) {
            currentUser.followReseller(resellerToFollow);
            System.out.println("You have 'like'd reseller: " + resellerToFollow.getFullName());
        } else {
            System.out.println("Reseller with UID " + uid + " not found.");
        }
    }

    public static List<Product> SearchProductsByName(String productName) {
        return products.stream()
                .filter(product -> product.getName().equalsIgnoreCase(productName))
                .collect(Collectors.toList());
    }

    public static List<Product> SearchProductsByCategory(int category) {
        List<Product> ProductSearch = new ArrayList<>();
        for (Product product : products) {
            if (product.getCategory() == category) {
                ProductSearch.add(product);
            }
        }
        return ProductSearch;
    }

    public static List<Product> SearchProductsByReseller(String resellerName) {
        List<Product> ProductSearch = new ArrayList<>();
        for (Product product : products) {
            if (product.getReseller().getFullName().equalsIgnoreCase(resellerName)) {
                ProductSearch.add(product);
            }
        }
        return ProductSearch;
    }

    public static List<Product> SearchProductsByPrice() {
        System.out.println("[1] Low -> High");
        System.out.println("[2] High -> Low");
        List<Product> ProductSearch = new ArrayList<>();
        Scanner scanner = new Scanner(System.in);
        int choice = 0;
        try {
            choice = scanner.nextInt();
        } catch (InputMismatchException e) {
            System.out.println("Invalid input. Please enter a valid number for your choice.");
            scanner.nextLine();
            SearchProductsByPrice();
        }
        if (choice == 1) {
            // Sort products by price Low -> High then return
            ProductSearch = Sort(1);
        } else if (choice == 2) {
            // Sort products by price High -> Low then return
            ProductSearch = Sort(2);
        } else {
            System.out.println("Invalid Option");
        }
        return ProductSearch;
    }

    public static List<Product> SearchProductsByRating() {
        return Sort(3);
    }

    public static List<Product> SearchProductsByLikes() {
        return Sort(4);
    }

    public static List<Product> SearchProductsByPromotions() {
        return Sort(5);
    }

    // TODO: Implement the different sorts
    private static List<Product> Sort(int choice) {
        List<Product> ProductList = products;
        // Price Low -> High
        if (choice == 1) {
            ProductList.sort(Comparator.comparing(Product::getPrice));
            // Price High -> Low
        } else if (choice == 2) {
            ProductList.sort(Comparator.comparing(Product::getPrice).reversed());
            // Likes High -> Low
        } else if (choice == 3) {
            ProductList.sort(Comparator.comparing(Product::getLikes).reversed());
            // Average Rating High -> Low
        } else if (choice == 4) {
            ProductList.sort(Comparator.comparing(Product::getAverageRating).reversed());
            // Promotion True/False
        } else if (choice == 5) {
            ProductList = ProductList.stream().filter(Product::isPromotion).collect(Collectors.toList());
        }
        return ProductList;
    }

    public Buyer ValidateBuyerUID(String UID) {
        for (Buyer buyer : buyers) {
            if (buyer.getUid().equals(UID)) {
                return buyer; // Buyer found, return the buyer
            }
        }
        return null;
    }

    public Reseller ValidateResellerUID(String UID) {
        for (Reseller reseller : resellers) {
            if (reseller.getUid().equals(UID)) {
                return reseller; // Reseller found, return the reseller
            }
        }
        return null;
    }

    // TODO: More functionalities to come

    public void Registration() {
        System.out.println("Welcome to UniShop:");
        System.out.println("[1] Register");
        System.out.println("[2] Sign In");
        System.out.println("[3] Continue as a guest");
        System.out.println("[4] Exit");
    }

    // Sign up as a buyer or Reseller
    public void SignUp(Scanner scanner) {
        System.out.println("[1] Register as a Buyer");
        System.out.println("[2] Register as a Reseller");
        int choice = 0;
        try {
            choice = scanner.nextInt();
        } catch (InputMismatchException e) {
            System.out.println("Invalid input. Please enter a valid number for your choice.");
            scanner.nextLine();
            SignUp(scanner);
        }
        String FirstName, LastName, UID, Email, Address, Password;

        switch (choice) {
            case 1 -> {
                // Register a buyer and add them to the ArrayList
                // ...
                // TODO: Implement Logic For Validating Registration information ie: Pattern
                // matching per profile attributes
                // ...
                try {
                    scanner.nextLine();
                    System.out.print("Enter buyer's first name: ");
                    FirstName = scanner.nextLine();
                    System.out.print("Enter buyer's last name: ");
                    LastName = scanner.nextLine();
                    System.out.print("Enter Unique Identifier: ");
                    UID = scanner.nextLine();
                    System.out.print("Enter buyer's email: ");
                    Email = scanner.nextLine();
                    System.out.print("Enter buyer's address: ");
                    Address = scanner.nextLine();
                    System.out.print("Enter buyer's password: ");
                    Password = scanner.nextLine();
                    Buyer buyer = new Buyer(FirstName, LastName, UID, Email, Address, Password);
                    addBuyer(buyer);
                } catch (InputMismatchException e) {
                    System.out.println("Invalid input. Please enter a valid number for your choice.");
                    scanner.nextLine();
                    SignUp(scanner);
                }
            }
            case 2 -> {
                // Register a reseller and add them to the ArrayList
                // ...
                // TODO: Implement Logic For Validating Registration information ie: Pattern
                // matching per profile attributes
                // ...
                try {
                    scanner.nextLine();
                    System.out.print("Enter reseller's first name: ");
                    FirstName = scanner.nextLine();
                    System.out.print("Enter reseller's last name: ");
                    LastName = scanner.nextLine();
                    System.out.print("Enter Unique Identifier: ");
                    UID = scanner.nextLine();
                    System.out.print("Enter reseller's email: ");
                    Email = scanner.nextLine();
                    System.out.print("Enter reseller's address: ");
                    Address = scanner.nextLine();
                    System.out.print("Enter reseller's password: ");
                    Password = scanner.nextLine();
                    Reseller reseller = new Reseller(FirstName, LastName, UID, Email, Address, Password);
                    addReseller(reseller);
                } catch (InputMismatchException e) {
                    System.out.println("Invalid input. Please enter a valid number for your choice.");
                    scanner.nextLine();
                    SignUp(scanner);
                }
            }
            default -> System.out.println("Invalid choice. Please enter a valid option.");
        }
    }

    public boolean SignIn(Scanner scanner) {
        // Sign in as a Buyer or a Reseller
        System.out.println("[1] Sign in as a Buyer");
        System.out.println("[2] Sign in as a Reseller");
        int choice = 0;
        String UID = null;
        try {
            choice = scanner.nextInt();

            scanner.nextLine();

            System.out.print("Enter your Unique Identifier (UID): ");
            UID = scanner.nextLine();
        } catch (InputMismatchException e) {
            System.out.println("Invalid input. Please enter a valid number for your choice.");
            scanner.nextLine();
            SignIn(scanner);
        }
        switch (choice) {
            case 1 -> {
                // Sign in as a buyer
                Buyer signedInBuyer = ValidateBuyerUID(UID);
                if (signedInBuyer != null) {
                    System.out.println("Sign-in as buyer successful. Welcome, " + signedInBuyer.getFirstName() + "!");
                    currentUser = signedInBuyer;
                    return true;
                } else {
                    System.out.println("Sign-in as buyer failed. UID not found.");
                    return false;
                }
            }
            case 2 -> {
                // Sign in as a reseller
                Reseller signedInReseller = ValidateResellerUID(UID);
                if (signedInReseller != null) {
                    System.out.println(
                            "Sign-in as reseller successful. Welcome, " + signedInReseller.getFirstName() + "!");
                    currentUser = signedInReseller;
                    return true;
                } else {
                    System.out.println("Sign-in as reseller failed. UID not found.");
                    return false;
                }
            }
            default -> System.out.println("Invalid choice. Please enter a valid option.");
        }
        return false;
    }

    public void run() {
        Scanner scanner = new Scanner(System.in);
        boolean running = true;

        while (running) {
            // Sign Up and Registration Display -> Main Menu
            Registration();
            int choice = 0;
            try {
                choice = scanner.nextInt();
            } catch (InputMismatchException e) {
                System.out.println("Invalid input. Please enter a valid number for your choice.");
                scanner.nextLine();
                Registration();
            }
            switch (choice) {
                case 1 -> SignUp(scanner);
                case 2 -> {
                    if (SignIn(scanner)) {
                        int menuChoice;
                        do {
                            menuChoice = currentUser.displayMenu(scanner);
                            if (menuChoice >= 1 && menuChoice <= 5) {
                                currentUser.sendToFunction(menuChoice, currentUser);
                            } else {
                                menuChoice = 6;
                            }
                        } while (menuChoice != 6);
                    }
                }
                case 3 -> {

                }
                case 4 -> running = false;
                default -> System.out.println("Invalid choice. Please enter a valid option.");
            }
        }
        System.out.println("Thank you for using UniShop!");
    }

    public static void main(String[] args) throws IOException {
        UniShop uniShop = new UniShop();
        Reseller Abby = new Reseller("Abby", "Dunham", "abbdun", "[email protected]", "2022 Abby rd", "abbdun");
        Reseller Shmidt = new Reseller("Shmidt", "Adams", "shmadms", "[email protected]", "2122 Shmidt rd", "shmadms");
        Reseller Christy = new Reseller("Christy", "Christo", "cristo", "[email protected]", "4122 rue LaPoule",
                "cristo");
        Reseller AnneSophie = new Reseller("Anne-Sophie", "Gauthier", "aneeso", "[email protected]",
                "4422 ave Victoria", "aneeso");
        Reseller Mathieu = new Reseller("Mathieu", "LeBlanc", "matleb", "[email protected]",
                "4022 boul LeBlanc", "matleb");
        Product Laptop = new Product("Asus Laptop", Abby, 4, 4, 1500.95);
        Product CalculusBook = new Product("Calculus Book", Shmidt, 1, 10, 35);
        Product NoteBooks = new Product("Notebooks", Christy, 3, 120, 25);
        Product GPU = new Product("Nvidia 3090 GPU", AnneSophie, 4, 1, 2000);
        Product Chair = new Product("Ikea Desk Chair", Mathieu, 5, 2, 105);
        Buyer John = new Buyer("John", "Smith", "johnsmith", "[email protected]", "2222 Smith rd", "johnsmith");
        Buyer Catherine = new Buyer("Catherine", "Parent", "catpar", "[email protected]", "2222 Smith rd", "catpar");
        Buyer Olivier = new Buyer("Olivier", "Lavinge", "ollav", "[email protected]", "2422 College ave", "ollav");
        Buyer Marie = new Buyer("Marie", "Desjardins", "mardej", "[email protected]", "2622 rue Madrigal", "mardej");
        Buyer Stephane = new Buyer("Stephane", "Ouest", "stephou", "[email protected]", "2822 Alton boul", "stephou");
        addReseller(Abby);
        addReseller(Shmidt);
        addReseller(Christy);
        addReseller(AnneSophie);
        addReseller(Mathieu);
        addBuyer(John);
        addBuyer(Catherine);
        addBuyer(Olivier);
        addBuyer(Marie);
        addBuyer(Stephane);
        uniShop.products.add(Laptop);
        uniShop.products.add(CalculusBook);
        uniShop.products.add(NoteBooks);
        uniShop.products.add(GPU);
        uniShop.products.add(Chair);

        Gson gson = new GsonBuilder()
            .serializeNulls()
            .setPrettyPrinting()
            .create();
        //Generating json file from UniShop object
        gson.toJson(uniShop, new FileWriter("./java/implementation/src/UniShop.json"));
        System.out.println(gson.toJson(uniShop));

        // uniShop.run();
    }
}

The expected behaviour is for it to print in the console the content of the object in JSON format and for that JSON to be stored in a file.

1
  • Honestly, that's a lot of code, which can't even compile, it's missing the definitions for Buyer, Product, etc. Please condense it to a minimal, reproducible example. Commented Dec 24, 2023 at 10:08

1 Answer 1

3

The fields inside the UniShop class that you want to serialize must be non-static, meaning you must make them instance fields. Secondly, you need to flush the FileWriter so the content will be written to the file:

...
FileWriter fileWriter = new FileWriter("/path/to/your/file");
gson.toJson(uniShop, fileWriter);
fileWriter.flush();
fileWriter.close();
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.