Before you start, I suggest you use the correct format ISO8601, that is 2018-07-11T23:15:15.600Z
.
To do the procedure Voce wants Voce 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;
}
}
}
Now you must create the instance of your Gson
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 ) );
}
}
It is possible and there are several alternatives ;P As you are doing so far, some specific problem?
– Bruno César
Yes, it is possible, you can register a
type adapter
for the types of time you want to treat, in this post is shown a complete example of how to do it in Gson. http://www.gitshah.com/2011/04/how-to-work-with-json-on-android-part-2.html– Ricardo Rodrigues de Faria