我开发了一个REST API,我正在尝试使用Android连接到它。以下是我的代码。
private void restCall()
{
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
YourEndpoints request = retrofit.create(YourEndpoints.class);
SetupBean setupBean = new SetupBean();
setupBean.setIdPatient(1);
setupBean.setCircleType(1);
setupBean.setFamiliarity(1);
setupBean.setValence(2);
setupBean.setArousal(3);
setupBean.setDateCreated(Common.getSQLCurrentTimeStamp());
setupBean.setLastUpdated(Common.getSQLCurrentTimeStamp());
Call<ResponseBody> yourResult = request.insertSetup(setupBean);
yourResult.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
try {
Log.d("MainActivity", "RESPONSE: " + response.errorBody().string());
}
catch(Exception e)
{
e.printStackTrace();
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
try {
t.printStackTrace();
Log.d("MainActivity", "RESPONSE: "+"FAILED");
}
catch(Exception e)
{
e.printStackTrace();
}
}
});
}
当我运行时,会显示以下错误
Can not construct instance of java.sql.Timestamp from String value 'Jun 9, 2016 4:24:37 PM': not a valid representation (error: Failed to parse Date value 'Jun 9, 2016 4:24:37 PM': Can not parse date "Jun 9, 2016 4:24:37 PM": not compatible with any of standard forms ("yyyy-MM-dd'T'HH:mm:ss.SSSZ", "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", "EEE, dd MMM yyyy HH:mm:ss zzz", "yyyy-MM-dd"))
因此转换Timestamp
似乎存在问题。在我的Bean
课程中,以下是Timestamp
的定义方式。
public void setDateCreated(Timestamp dateCreated) {
this.dateCreated = dateCreated;
}
public Timestamp getLastUpdated() {
return lastUpdated;
}
在我的restCall()
方法中,我调用Common.getSQLCurrentTimeStamp()
来生成时间戳。以下是该方法。
public static Timestamp getSQLCurrentTimeStamp()
{
java.util.Date date = new java.util.Date();
Timestamp t = new Timestamp(date.getTime());
System.out.println(t);
return t;
}
因此,当我运行restCall()
方法时,为什么会出现此Can not construct instance of java.sql.Timestamp from String value 'Jun 9, 2016 4:24:37 PM': not a valid representation (error: Failed to parse Date value 'Jun 9, 2016 4:24:37 PM': Can not parse date "Jun 9, 2016 4:24:37 PM": not compatible with any of standard forms ("yyyy-MM-dd'T'HH:mm:ss.SSSZ", "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", "EEE, dd MMM yyyy HH:mm:ss zzz", "yyyy-MM-dd"))
错误?我该如何解决?
答案 0 :(得分:1)
我自己解决了这个问题。 Retrofit 2
正在使用GSON,因此您必须手动提供日期时间转换器
Gson gson = new GsonBuilder()
.setDateFormat("yyyy-MM-dd'T'HH:mm:ss")
.create();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(URL)
.addConverterFactory(GsonConverterFactory.create(gson))
.build();