我正在尝试使用注释来控制序列化格式。但是似乎没有任何方法可以从 TypeAdapter 或 TypeAdapterFactory 内部访问字段注释。
这是我正在努力实现的一个例子。
import org.joda.time.DateTime;
public class Movie {
String title;
@DateTimeFormat("E, M d yyyy")
DateTime releaseDate;
// other fields ...
}
public class LogEvent {
String message;
@DateTimeFormat("yyyyMMdd'T'HHmmss.SSSZ")
DateTime timestamp;
}
对于 Movie 对象,我想将日期序列化为“2013 年 8 月 24 日,星期六”,但对于 LogEvent,我想将日期序列化为“20130824T103025.123Z”。
我试图做到这一点,而不必为每个类编写单独的 TypeAdapterFactory(想象一下,如果我们有 100 个不同的类,其中的 DateTime 字段需要不同的格式)
TIA!
最佳答案
这是一个方法。这个想法是使用 TypeAdapterFactory
来加载您的类。然后在加载对象后,检测 DateTime
类型的字段以应用注释并替换值。
不知道如何存储 DateTime
对象,因此您可能需要使用 getAsJsonObject
而不是 getAsJsonPrimitive
。
final class MyAdapter implements TypeAdapterFactory {
@Override
public <T> TypeAdapter<T> create(final Gson gson, final TypeToken<T> tokenType) {
final TypeAdapter<T> adapter = gson.getDelegateAdapter(this, tokenType);
return new TypeAdapter<T>() {
@Override
public T read(JsonReader reader) throws IOException {
JsonElement tree = gson.getAdapter(JsonElement.class).read(reader);
T out = adapter.fromJsonTree(tree);
// important stuff here
Class<? super T> cls = tokenType.getRawType();
for (Field field : cls.getDeclaredFields()) {
if (DateTime.class.isAssignableFrom(field.getType())) {
DateTimeFormat ano = field.getAnnotation(DateTimeFormat.class);
if (ano != null) {
JsonPrimitive val = ((JsonObject) tree).getAsJsonPrimitive(field.getName());
String format = ano.value();
DateTime date = // .. do your format here
field.set(out, date);
}
}
}
return out;
}
@Override
public void write(JsonWriter writer, T value) throws IOException {
}
};
}
}
关于java - GSON通过注解控制序列化格式化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18424615/