2013-10-08 14 views
10

I teraz, gdy chcę powiedzieć gson Jak analizować dat robię:Konfiguracja Gson korzystać z kilku formatów daty

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

Ale mam również pola tylko dzień, a inni tylko raz, i chcę, aby oba były przechowywane jako obiekty Date. Jak mogę to zrobić?

Odpowiedz

11

Ten niestandardowy serializer/deserializer obsługuje wiele formatów. Najpierw spróbuj wykonać parsowanie w jednym formacie, a jeśli to się nie powiedzie, spróbuj z drugim formatem. Powinno to również obsługiwać daty zerowe bez wysadzania w powietrze.

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; 
    } 
} 

} 

Nadzieję, że pomaga, powodzenia w projekcie.

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

Powyższy kod zastosuje nowy stworzony GsonDateDeSerializer jak GSON Data serializatora który stworzonej przez @reggoodwin

0

Dla dokładniejszego sterowania poszczególnych dziedzinach, może być korzystne do kontrolowania formatu poprzez adnotacje:

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

... z adapterem typu wzdłuż następujących linii:

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)... 
    } 
}