Before starting, I suggest that you use the correct ISO8601 format, which is 2018-07-11T23:15:15.600Z
.
To do the procedure you want you will have to implement com.google.gson.TypeAdapter<Timestamp>
Example:
public static class MyDateTypeAdapter extends TypeAdapter< Timestamp > {
private final SimpleDateFormat dataEhora = new SimpleDateFormat( "yyyy/MM/dd'T'hh:mm:ss.SSS" );
private final SimpleDateFormat data = new SimpleDateFormat( "yyyy/MM/dd" );
@Override
public void write( JsonWriter out, Timestamp value ) throws IOException {
if ( value == null ) {
out.nullValue();
} else {
if ( value.getNanos() == 0 && value.getSeconds() == 0 && value.getMinutes() == 0 && value.getHours() == 0 ) {
out.value( this.data.format( value ) );
} else {
out.value( this.dataEhora.format( value ) );
}
}
}
@Override
public Timestamp read( JsonReader in ) throws IOException {
if ( in != null ) {
String dataString = in.nextString();
final SimpleDateFormat format;
if ( dataString.length() == 10 ) {
format = this.data;
} else {
format = this.dataEhora;
}
Date parsedDate;
try {
parsedDate = format.parse( dataString );
return new Timestamp( parsedDate.getTime() );
} catch ( ParseException e ) {
return null;
}
} else {
return null;
}
}
}
You should now create the instance of your Gson
by setting the created adapter, see below:
class Exemplo {
Timestamp dataComHora;
Timestamp data;
}
class Teste {
public static void main( String[] args ) {
Gson gson = new GsonBuilder().registerTypeAdapter( Timestamp.class, new MyDateTypeAdapter() ).create();
String json = "{\"dataComHora\":\"2018/07/11T11:30:13.795\",\"data\":\"2018/08/11\"}";
System.out.println( "entrada: " + json );
Exemplo exemplo = gson.fromJson( json, Exemplo.class );
System.out.println( "saida: " + gson.toJson( exemplo ) );
}
}