package ru.hexaend.orderManagments; import com.google.gson.Gson; import…
- User
package ru.hexaend.orderManagments;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import ru.hexaend.orderManagments.models.Customer;
import ru.hexaend.orderManagments.models.Order;
import ru.hexaend.orderManagments.models.Product;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.lang.reflect.Type;
import java.time.LocalDate;
import java.util.*;
public class Main {
public static void main(String[] args) throws FileNotFoundException {
List products = new ArrayList();
Set customers = new HashSet();
Map<Integer, Order> orders = new HashMap<Integer, Order>();
Gson gson = new GsonBuilder().registerTypeAdapter(LocalDate.class, new LocalDateTypeAdapter()) .create(); Type type = new TypeToken<Map<Integer, Order>>() { }.getType(); Order order = new Order(1, new Customer(1, "asd", "2"), products, LocalDate.now()); System.out.println(gson.toJson(order, type));// System.out.println(Optional.ofNullable(gson.fromJson(new FileReader("orders.json"), type)));
} }
Exception in thread "main" java.lang.ClassCastException: class ru.hexaend.orderManagments.models.Order cannot be cast to class java.util.Map (ru.hexaend.orderManagments.models.Order is in unnamed module of loader 'app'; java.util.Map is in module java.base of loader 'bootstrap')
at com.google.gson.internal.bind.MapTypeAdapterFactory$Adapter.write(MapTypeAdapterFactory.java:154)
at com.google.gson.Gson.toJson(Gson.java:944)
at com.google.gson.Gson.toJson(Gson.java:899)
at com.google.gson.Gson.toJson(Gson.java:848)
at ru.hexaend.orderManagments.Main.main(Main.java:27)
- Assistant
The
ClassCastExceptionyou're encountering is due to the fact that you're trying to serialize anOrderobject using aTypeTokenthat specifies aMap<Integer, Order>. This discrepancy is causing the exception because Gson is expecting aMap, but you're providing a single .
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.