gson.toJson返回空对象[已关闭]

ifmq2ha2  于 10个月前  发布在  其他
关注(0)|答案(1)|浏览(184)

**已关闭。**此问题需要debugging details。目前不接受回答。

编辑问题以包括desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem。这将帮助其他人回答问题。
14天前关门了。
Improve this question
我需要为我的一个uni项目序列化java对象,但我没有太多的java经验。我想知道为什么toJson在我尝试打印它时总是返回一个空对象,为什么它不在文件中写入任何内容。
这是我的代码

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

字符串
预期的行为是在控制台中以JSON格式打印对象的内容,并将JSON存储在文件中。

p8ekf7hl

p8ekf7hl1#

要序列化的UniShop类中的字段必须是非静态的,这意味着必须将它们设置为示例字段。其次,需要刷新FileWriter,以便将内容写入文件:

...
FileWriter fileWriter = new FileWriter("/path/to/your/file");
gson.toJson(uniShop, fileWriter);
fileWriter.flush();
fileWriter.close();

字符串

相关问题