GSON-Format daty

Próbuję mieć niestandardowy format daty w wyjściu Gson, ale .setDateFormat(DateFormat.FULL) nie działa i tak samo jest z .registerTypeAdapter(Date.class, new DateSerializer()).

To tak, jakby Gson nie dbał o obiekt "Data" i wydrukował go na swojej drodze.

Jak mogę to zmienić?

Dzięki

EDIT:

@Entity
public class AdviceSheet {
  public Date lastModif;
[...]
}

public void method {
   Gson gson = new GsonBuilder().setDateFormat(DateFormat.LONG).create();
   System.out.println(gson.toJson(adviceSheet);
}

Zawsze używam java.util.Date; setDateFormat() nie działa: (

 153
Author: giampaolo, 2011-07-29

6 answers

Wydaje się, że musisz zdefiniować formaty zarówno dla części daty, jak i czasu lub użyć formatowania opartego na łańcuchach znaków. Na przykład:

Gson gson = new GsonBuilder()
   .setDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz").create();

Lub za pomocą Javy.tekst.DateFormat

Gson gson = new GsonBuilder()
   .setDateFormat(DateFormat.FULL, DateFormat.FULL).create();

Lub zrób to z serializerami:

Uważam, że formatery nie mogą tworzyć znaczników czasu, ale ta para serializer / deserializer wydaje się działać

JsonSerializer<Date> ser = new JsonSerializer<Date>() {
  @Override
  public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext 
             context) {
    return src == null ? null : new JsonPrimitive(src.getTime());
  }
};

JsonDeserializer<Date> deser = new JsonDeserializer<Date>() {
  @Override
  public Date deserialize(JsonElement json, Type typeOfT,
       JsonDeserializationContext context) throws JsonParseException {
    return json == null ? null : new Date(json.getAsLong());
  }
};

Gson gson = new GsonBuilder()
   .registerTypeAdapter(Date.class, ser)
   .registerTypeAdapter(Date.class, deser).create();
 262
Author: M.L.,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-11-06 22:01:13
Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").create();

Powyższy format wydaje mi się lepszy, ponieważ ma precyzję do Milis.

Edytował format cytowania "Z"

 55
Author: tj-recess,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-01-29 19:58:02

Jak zauważył M. L., działa tutaj JsonSerializer. Jeśli jednak formatujesz jednostki bazy danych, użyj Javy.sql.Data rejestracji użytkownika serializer. Deserializer nie jest potrzebny.

Gson gson = new GsonBuilder()
   .registerTypeAdapter(java.sql.Date.class, ser).create();

Ten raport o błędzie może być powiązany: http://code.google.com/p/google-gson/issues/detail?id=230 . używam jednak wersji 1.7.2.

 4
Author: Milanka,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-11-22 08:48:56

W przypadku, gdy nienawidzisz klas wewnętrznych, korzystając z funkcjonalnego interfejsu, możesz napisać mniej kodu w Java 8 za pomocą wyrażenia lambda.

JsonDeserializer<Date> dateJsonDeserializer = 
     (json, typeOfT, context) -> json == null ? null : new Date(json.getAsLong());
Gson gson = new GsonBuilder().registerTypeAdapter(Date.class,dateJsonDeserializer).create();
 4
Author: Karthik,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-02-24 20:56:11

Możesz określić format Gson gson = builder.setDateFormat("yyyy-MM-dd").create(); w tej metodzie zamiast yyyy-MM-dd możesz użyć dowolnego innego formatu

 GsonBuilder builder = new GsonBuilder();
                        builder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {
                            public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
                                return new Date(json.getAsJsonPrimitive().getAsLong());
                            }
                        });

                        Gson gson = builder.setDateFormat("yyyy-MM-dd").create();
 0
Author: Abhijit Chakra,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-09-10 10:54:19

To w ogóle nie zadziała. W JSON nie ma Typu daty. Polecam serializować do ISO8601 tam iz powrotem (dla formatu agnostics i js compat). Pamiętaj, że musisz wiedzieć, które pola zawierają daty.

 -1
Author: Michael-O,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-07-29 15:44:20