這可能嗎?
的排序。不幸的是,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