gpt4 book ai didi

java - 使用Gson以自定义方式将Date对象序列化为JSON(注释)

转载 作者:行者123 更新时间:2023-12-02 02:48:13 27 4
gpt4 key购买 nike

我有以下类结构

class A {
B b;
}

class B {
@CustomDateFormat(
format = "yyyy-MM-dd"
)
protected Date creationDate;
}

我想将 A 类的实例序列化为 JSON,输出 JSON 具有使用注释 @CustomDateFormat 中的值进行格式化的creationDate 字段。是否可以?最好使用 Gson。这将在 Android 上执行,因此 Java 8 不具备 ATM 功能。

提前感谢您的任何想法

最佳答案

Is it possible?

有点。不幸的是,Gson 几乎不支持自定义注解。但是,Gson 对其 @JsonAdapter 注释提供 native 支持,以便您可以模拟自定义注释。

比方说,

final class A {

final B b;

A(final B b) {
this.b = b;
}

}
final class B {

// Here comes an emulation for @CustomDateFormat(format = "yyyy-MM-dd")
@JsonAdapter(YyyyMmDdDateTypeAdapter.class)
final Date creationDate;

B(final Date creationDate) {
this.creationDate = creationDate;
}

}
abstract class AbstractDateTypeAdapter
extends TypeAdapter<Date> {

protected abstract DateFormat getDateFormat();

@Override
@SuppressWarnings("resource")
public final void write(final JsonWriter out, final Date value)
throws IOException {
out.value(getDateFormat().format(value));
}

@Override
public final Date read(final JsonReader in) {
throw new UnsupportedOperationException("Not implemented");
}

}
final class YyyyMmDdDateTypeAdapter
extends AbstractDateTypeAdapter {

// Let Gson do it itself when needed
private YyyyMmDdDateTypeAdapter() {
}

@Override
protected DateFormat getDateFormat() {
// SimpleDateFormat is known to be thread-unsafe so it has to be created everytime it's necessary
// Maybe Joda Time is an option for you?
// Joda Time date formatters are thread-safe and can be safely instantiated once per application
return new SimpleDateFormat("yyyy-MM-dd");
}

}

示例:

private static final Gson gson = new Gson();

public static void main(final String... args) {
final A a = new A(new B(new Date()));
final String json = gson.toJson(a);
System.out.println(json);
}

输出:

{"b":{"creationDate":"2017-05-29"}}

关于java - 使用Gson以自定义方式将Date对象序列化为JSON(注释),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44241514/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com