2013-10-08 12 views
10

io ora che quando voglio dire GSON come analizzare le date che faccio:Configurare GSON utilizzare diversi formati di data

Gson gson= new GsonBuilder().setDateFormat("yyyy-MM-dd hh:mm").create(); 

Ma ho anche i campi con solo la data, e gli altri con solo il tempo, e voglio che entrambi vengano memorizzati come oggetti Date. Come posso fare questo?

risposta

11

Questo serializzatore/deserializzatore personalizzato può gestire più formati. Si potrebbe provare prima l'analisi in un formato, quindi se fallisce, provare con un secondo formato. Questo dovrebbe anche gestire le date nulle senza esplodere.

public class GsonDateDeSerializer implements JsonDeserializer<Date> { 

... 

private SimpleDateFormat format1 = new SimpleDateFormat("MMM dd, yyyy hh:mm:ss a"); 
private SimpleDateFormat format2 = new SimpleDateFormat("HH:mm:ss"); 

... 

@Override 
public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { 
    try { 
     String j = json.getAsJsonPrimitive().getAsString(); 
     return parseDate(j); 
    } catch (ParseException e) { 
     throw new JsonParseException(e.getMessage(), e); 
    } 
} 

private Date parseDate(String dateString) throws ParseException { 
    if (dateString != null && dateString.trim().length() > 0) { 
     try { 
      return format1.parse(dateString); 
     } catch (ParseException pe) { 
      return format2.parse(dateString); 
     } 
    } else { 
     return null; 
    } 
} 

} 

Spero che ti aiuti, buona fortuna per il tuo progetto.

4
GsonBuilder builder = new GsonBuilder(); 
builder.registerTypeAdapter(Date.class, new GsonDateDeSerializer()); 
gson = builder.create(); 

Sopra codice si applica la nuova creato GsonDateDeSerializer come GSON Data serializzatore che ha creato dagli @reggoodwin

0

Per un controllo più fine dei singoli campi, può essere preferibile per controllare il formato, tramite annotazioni:

@JsonAdapter(value = MyDateTypeAdapter.class) 
private Date dateField; 

... con l'adattatore di tipo lungo queste linee:

public class MyDateTypeAdapter extends TypeAdapter<Date> { 
    @Override 
    public Date read(JsonReader in) throws IOException { 
     // If in.peek isn't JsonToken.NULL, parse in.nextString()() appropriately 
     // and return the Date... 
    } 

    @Override 
    public void write(JsonWriter writer, Date value) throws IOException { 
     // Set writer.value appropriately from value.get() (if not null)... 
    } 
} 
Problemi correlati