这可能吗?
的排序。不幸的是,Gson几乎不支持自定义注释。但是,Gson对其@JsonAdapter
注释进行本地支持,以便您可以模拟自定义注释。
比方说,
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年5月29日”}}
确实不是恒定的。然而,使用反射也不是微不足道的,因为我不知道究竟哪一个Date成员被序列化了。 新JsonSerializer(){ @覆盖 公共JsonElement连载(日期SRC,类型typeOfSrc,JsonSerializationContext上下文){// 在大多数情况下使用YYYY-MM-DD,因此把它作为备用 日期格式字符串=“yyyy-MM-dd”; } } –
hhg
换句话说......我将不得不使用Fields作为成员来构建一个类。这会让我回注释。最后用一个自定义的JsonSerializer编排这些内容。它看起来对我诉哈克,但没有更好的主意 –
hhg