[英]Custom gson deserializer for Date never gets called
据我所知,gson 不会自动将 java.util.Date 对象序列化和反序列化为 ISO 字符串,例如“yyyy-MM-ddTHH:mm:ssZ”或例如“2014-04-15T18:22:00-05 :00”。 因此,为了让我在客户端(使用带有 gson 的 Retrofit)和服务器之间正确地传达日期,我需要将 DateFormat 指定为 gson。 这是我所做的:
// code defining the creation of a RestAdapter
// ...
new GsonBuilder()
.setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ")
.create()
添加 .setDateFormat 行足以让 gson 正确地将时间戳字符串反序列化为 Date 对象。 但是,它没有将 Date 对象序列化为时间戳字符串。 所以我假设我必须像这样创建一个自定义序列化程序:
// code defining the creation of a RestAdapter
// ...
new GsonBuilder()
.setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ")
.registerTypeAdapter(Date.class, new DateSerializer())
.create()
和 DateSerializer 类:
class DateSerializer implements JsonSerializer<Date> {
@Override
public JsonElement serialize(Date arg0, Type arg1, JsonSerializationContext arg2) {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ", Locale.US);
return new JsonPrimitive(df.format(arg0));
}
}
不幸的是,序列化函数被忽略了。 相反,gson 将日期格式化为字符串,如“Tues Mar 15 18:22:00 EST 2014”。 所以为了测试,我尝试用以下内容替换序列化函数:
public JsonElement serialize(Date arg0, Type arg1, JsonSerializationContext arg2) {
throw new RuntimeException("Serialize function called!");
}
但当然 RuntimeException 永远不会被抛出。
有谁知道为什么我的序列化函数被忽略? 我想我在某处读到,对于某些类型,如果为超类定义了一个 registerTypeAdapter,则将被忽略,但由于这是 java.util.Date,如果这是问题,我会感到困惑。 我可能只是在做一些愚蠢的事情,但我可能不太了解 Date 或 gson,无法意识到这一点。
编辑:提供有关以下代码的更多上下文:
我的应用程序
public class MyApplication extends Application {
public static RestAdapter restAdapter;
public static The1Api the1Api;
public static void createRestAdapter(String server_url){
// enable cookies
CookieManager cookieManager = new CookieManager();
cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
CookieHandler.setDefault(cookieManager);
// create rest adapter
restAdapter = new RestAdapter.Builder()
.setEndpoint(server_url)
.setConverter(new GsonConverter(new GsonBuilder()
.setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ")
.registerTypeAdapter(Date.class, new DateSerializer())
.create()))
.setLogLevel(LogLevel.FULL)
.setLog(new ResponseInterceptor())
.build();
// create API
the1Api = restAdapter.create(The1Api.class);
}
}
The1Api.java
public interface The1Api {
/* Chat */
public class PublicMessage {
String from_user;
String message;
Date time;
Integer microsecond;
Boolean in_1_percent;
}
public class PublicMessageList {
Integer last_message_id;
ArrayList<PublicMessage> messages;
}
@GET("/chat/get_public_messages/")
public PublicMessageList getPublicMessages(
@Query("last_message_id") Integer last_message_id, // optional
@Query("since") Date since, // optional
@Query("max") Integer max // optional
);
// ...
}
登录活动.java
public class LoginActivity extends Activity {
// ...
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Crashlytics.start(this);
MyApplication.createRestAdapter(getString(R.string.server_url));
setContentView(R.layout.activity_login);
}
@Override
protected void onPostCreate(Bundle savedInstanceState){
super.onPostCreate(savedInstanceState);
Thread thread = new Thread(){
@Override
public void run(){
ArrayList<The1Api.PublicMessage> publicMessages = MyApplication.the1Api.getPublicMessages(null, null, null).messages;
for (The1Api.PublicMessage m : publicMessages){
Log.d("The1", "[" + m.time.toString() + "] " + m.from_user + ": " + m.message);
}
// when the following line gets executed, my server receives a request including the date below,
// but the server does not understand the format of the date because it does not get serialized properly
MyApplication.the1Api.getPublicMessages(null, new Date(1000000000), null);
}
};
thread.start();
}
// ...
}
日期序列化程序
class DateSerializer implements JsonSerializer<Date> {
@Override
public JsonElement serialize(Date arg0, Type arg1, JsonSerializationContext arg2) {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ", Locale.US);
return new JsonPrimitive(df.format(arg0));
}
}
编辑 2:目前还没有解决方案,但作为一种解决方法,您可以在发送日期之前手动将日期转换为其他格式。 在 Kalel 建议将其转换为 String 的评论中,我将其转换为 Long(自 UNIX 时代以来的秒数)。
您仍然能够复制此问题吗? 我看到 Gson 正确序列化和反序列化。 这可能是一个 Retrofit 问题(我以前没有使用过它),但是查看GsonConverter
的文档,我认为除了委托给Gson
对象中提供的对象之外,没有理由做任何其他事情。
这是一个 SSCCE:
public class GsonDateDemo {
public static void main(String[] args) {
Gson gson = new GsonBuilder()
.setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ")
.registerTypeAdapter(Date.class, new DateSerializer())
.create();
Date d = new Date(1438806977000L);
System.out.println("Serializing "+d);
String json = gson.toJson(d);
System.out.println("JSON: "+json);
Date d2 = gson.fromJson(json, Date.class);
System.out.println("Deserialized: "+d2);
System.out.println("Equal? "+d.equals(d2));
}
static class DateSerializer implements JsonSerializer<Date> {
@Override
public JsonElement serialize(Date arg0, Type arg1, JsonSerializationContext arg2) {
System.out.println("Serializer received "+arg0);
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ", Locale.US);
return new JsonPrimitive(df.format(arg0));
}
}
}
这输出:
Calling: local.GsonDateDemo.main[]
Serializing Wed Aug 05 16:36:17 EDT 2015
Serializer received Wed Aug 05 16:36:17 EDT 2015
JSON: "2015-08-05T16:36:17-0400"
Deserialized: Wed Aug 05 16:36:17 EDT 2015
Equal? true
如果可以,请修改此 SSCCE 以使用 Retrofit 并查看是否可以通过这种方式复制故障。
gson 中的问题,当我们尝试在调用setDateFormat
之后反序列化时,自定义DateDesializer
没有调用。
所以当你反序列化时不要调用setDateFormat
;)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.