我正在使用rest api,而我遇到了这个问题
java.lang.IndexOutOfBoundsException: Invalid time zone indicator '0'
基本上我是使用Gson将Json转换为我的班级
Gson gson = new Gson();
MyResponse myResponse = gson.fromJson(responseService.getNumber(id), MyResponse.class);
但是我像这样在json中有一个日期
"date": 1375412400000
如何在日期上转换为模型类?要转换并显示例如02/25/2018吗?
MyResponse.class
public class MyResponse {
List<Dados> dados;
public List<Dados> getDados() {
return dados;
}
public void setDados(List<Dados> dados) {
this.dados = dados;
}
}
ResponseService.class
public interface ResponseService {
@GetMapping("/search/rg/{rg}")
String getDados(@PathVariable("rg") String rg);
}
Dados.Class
public class Dados {
@JsonFormat(shape = JsonFormat.Shape.STRING,pattern="dd/MM/yyyy",locale = "pt-BR", timezone = "Brazil/East")
@DateTimeFormat(pattern = "dd/MM/yyyy")
@Temporal(TemporalType.DATE)
Date data;
String codigo;
String estado;
String cidade;
String oriundo;
...gets and setters
}
答案 0 :(得分:0)
我找到了解决方案。 首先,我必须设定日期
ErrorActivity
在我必须创建一个类以反序列化日期之后
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.setDateFormat("M/d/yy hh:mm a");
然后我在gsonbuilder中使用了我的课程
import java.lang.reflect.Type;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
public class DateDeserializer implements JsonDeserializer<Date> {
@Override
public Date deserialize(JsonElement element, Type arg1,
JsonDeserializationContext arg2) throws JsonParseException {
String date = element.getAsString();
SimpleDateFormat formatter = new SimpleDateFormat("M/d/yy hh:mm a");
formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
try {
return formatter.parse(date);
} catch (ParseException e) {
System.err.println("Failed to parse Date due to:", e);
return null;
}
}
}