小编pas*_*ika的帖子

使用GSON将java.time.LocalDateTime(java 8)序列化为js Date的最佳实践

在我们最近的项目中,我们使用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对象.它工作正常.

我需要知道,这种方式还可以,还是有更好的方法来做到这一点?

javascript java serialization gson

14
推荐指数
2
解决办法
2万
查看次数

Dart:在foreach循环中从if退出函数

我想在 if语句,但我无法这样做。

下面是我的代码片段。

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();
  }
Run Code Online (Sandbox Code Playgroud)

谢谢。

foreach loops break dart flutter

3
推荐指数
2
解决办法
2747
查看次数

标签 统计

break ×1

dart ×1

flutter ×1

foreach ×1

gson ×1

java ×1

javascript ×1

loops ×1

serialization ×1