Reputation: 191
Json string given by Jackson contains time as {"time":"19:31:00"}
I want to deserialize it using Gson to get the java.sql.Time
object back.
What DateFormat should I set into gson?
Presently, I am using
Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss").create();
Upvotes: 1
Views: 1351
Reputation: 1755
You can register a JSONDeserializer for java.sql.Time
with Gson.
public static void main(String[] args) {
Gson gson = new GsonBuilder().registerTypeAdapter(Time.class, new MyTimeJsonDeserializer()).create();
MyTime time = gson.fromJson("{\"time\": \"19:31:00\"}", MyTime.class);
System.out.println(time.getTime());
}
public static class MyTime{
private Time time;
public Time getTime() {
return time;
}
public void setTime(Time time) {
this.time = time;
}
}
public static class MyTimeJsonDeserializer implements JsonDeserializer<Time>{
@Override
public Time deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException {
String time = json.getAsString();
String[] parts = time.split(":");
return new Time(Integer.parseInt(parts[0]), Integer.parseInt(parts[1]), Integer.parseInt(parts[2]));
}
}
Upvotes: 2
Reputation: 7711
Try to first get the date as a string, and then convert it to date using new SimpleDateFormat("HH:mm:ss").parse(timeStr)
Upvotes: 0