在我们最近的项目中,我们使用java 8.我需要将java.time.LocalDateTime序列化为java脚本的日期格式.
目前我所做的是定义一个自定义序列化程序,将LocalDateTime转换为时间戳.
public class LocalDateTimeSerializer implements JsonSerializer<LocalDateTime> {
@Override
public JsonElement serialize(LocalDateTime localDateTime, Type type, JsonSerializationContext jsonSerializationContext) {
Instant instant = localDateTime.atZone(ZoneId.systemDefault()).toInstant();
Date date = Date.from(instant);
return new JsonPrimitive(date.getTime());
}
}
Run Code Online (Sandbox Code Playgroud)
然后使用GsonBuilder和我的自定义LocalDateTimeSerializer创建Gson对象
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(LocalDateTime.class, new LocalDateTimeSerializer());
Gson gson = gsonBuilder.create();
Run Code Online (Sandbox Code Playgroud)
然后在Java Script中,我使用此时间戳创建一个Date对象.它工作正常.
我需要知道,这种方式还可以,还是有更好的方法来做到这一点?
我想在 if语句,但我无法这样做。
下面是我的代码片段。
Run Code Online (Sandbox Code Playgroud)void addOrderToCart(Product product, int quantity, String color, String size) { _lastOrder = Order(product, quantity, _orderId++, color, size); _orders.forEach((element) { if(element.product.id == _lastOrder.product.id){ element.colors.add(color); element.sizes.add(size); element.quantity = element.quantity + quantity; notifyListeners(); return; } }); _orders.add(_lastOrder); notifyListeners(); }
谢谢。