Antes de começar, sugiro que use o formato correto ISO8601, que é 2018-07-11T23:15:15.600Z
.
Para fazer o procedimento que voce quer voce terá que implementar com.google.gson.TypeAdapter<Timestamp>
Exemplo:
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;
}
}
}
Agora você deve criar a instância do seu Gson
setando o adapter criado, veja abaixo:
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 ) );
}
}
type adapter
para os tipos de tempo que você quer tratar, neste post é mostrado um exemplo completo de como fazê-lo no Gson. gitshah.com/2011/04/… – Ricardo Rodrigues de Faria 11/11/15 às 13:38