“Нерозбірлива дата: 1302828677828”, яка намагається десеріалізувати за допомогою Gson дату формату мілісекунди, отриману від сервера


80

Через 4 години безперервно намагаючись вирішити проблему, я вирішив запитати тут, чи хтось може мені допомогти.

Проблема полягає в тому, що мій клієнт Android при спробі десеріалізувати дані, отримані від сервера, видає виняток "Unparseable: 1302828677828".

Я хотів би знати, чи можна десеріалізувати дату формату мілісекунд за допомогою Gson.


Яку дату / час це повинно представляти?
Squonk

Чи не можете ви просто проаналізувати його як a long, а потім програмно перетворити longa Dateна ваш код?
aroth

11
Нарешті я отримав рішення: // Створює об’єкт json, який буде керувати отриманою інформацією GsonBuilder builder = new GsonBuilder (); // Зареєструйте адаптер для управління типами дат як довгі значення builder.registerTypeAdapter (Date.class, new JsonDeserializer <Date> () {public Date deserialize (JsonElement json, Type typeOfT, JsonDeserializationContext context) кидає JsonParseException {return new Date (json .getAsJsonPrimitive (). getAsLong ());}}); Gson gson = builder.create ();
Альфонсо,

Відповіді:


147

Коментар Альфонсо:

Нарешті я отримав рішення:

// Creates the json object which will manage the information received 
GsonBuilder builder = new GsonBuilder(); 

// Register an adapter to manage the date types as long values 
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.create();

Дякую тобі, що ти врятував мій час !!
Кріс Сім

проблеми з
часовим

Дякую, це допомогло і мені. Хоча я використовував це для Timestamp.
Феру

це працює для кожної дати, яка передається в мілісекундах, а не для передачі правила для будь-якого виду синтаксичного аналізу
Nather Webber

2
.getAsJsonPrimitive()можна опустити, а з лямбдами Java 8 це ще коротше:Gson gson = new GsonBuilder().registerTypeAdapter(Date.class, (JsonDeserializer) (json, typeOfT, context) -> new Date(json.getAsLong())).create();
gmk57,

2

Я написав ImprovedDateTypeAdapter на основі GST за замовчуванням DateTypeAdapter, який підтримує формат дат за замовчуванням та формат позначки часу (довгий).

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.TypeAdapter;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.JsonWriter;

import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;

public final class ImprovedDateTypeAdapter extends TypeAdapter<Date> {

    public static final TypeAdapterFactory FACTORY = new TypeAdapterFactory() {

        public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) {

            @SuppressWarnings("unchecked")
            TypeAdapter<T> typeAdapter = (TypeAdapter<T>) ((typeToken.getRawType() == Date.class) ? new ImprovedDateTypeAdapter()
                    : null);
            return typeAdapter;
        }
    };
    private final DateFormat enUsFormat;
    private final DateFormat localFormat;
    private final DateFormat iso8601Format;

    public ImprovedDateTypeAdapter() {
        this.enUsFormat = DateFormat.getDateTimeInstance(2, 2, Locale.US);

        this.localFormat = DateFormat.getDateTimeInstance(2, 2);

        this.iso8601Format = buildIso8601Format();
    }

    private static DateFormat buildIso8601Format() {
        DateFormat iso8601Format = new SimpleDateFormat(
                "yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.US);
        iso8601Format.setTimeZone(TimeZone.getTimeZone("UTC"));
        return iso8601Format;
    }

    public Date read(JsonReader in) throws IOException {
        if (in.peek() == JsonToken.NULL) {
            in.nextNull();
            return null;
        }
        return deserializeToDate(in.nextString());
    }

    private synchronized Date deserializeToDate(String json) {
        try {

            return new Date(Long.parseLong(json));
        } catch (Exception e) {

            try {

                return this.localFormat.parse(json);
            } catch (ParseException e1) {

                try {

                    return this.enUsFormat.parse(json);
                } catch (ParseException e2) {

                    try {

                        return this.iso8601Format.parse(json);
                    } catch (ParseException e3) {

                        throw new JsonSyntaxException(json, e3);
                    }
                }
            }
        }
    }

    public synchronized void write(JsonWriter out, Date value)
            throws IOException {
        if (value == null) {
            out.nullValue();
            return;
        }
        String dateFormatAsString = this.enUsFormat.format(value);
        out.value(dateFormatAsString);
    }
}

Щоб використовувати його:

// Creates the json object which will manage the information received 
GsonBuilder builder = new GsonBuilder(); 

// Register an adapter to manage the date types as long values 
builder.registerTypeAdapter(Date.class, new ImprovedDateTypeAdapter());

Gson gson = builder.create();

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

JsonDeserializer<Date> deserializer= 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, serializer)
   .registerTypeAdapter(Date.class, deserializer).create();

1

Використовуйте фрагмент нижче для перетворення мілісекунд у Дату під час обробки JSON.

    GsonBuilder gsonBuilder = new GsonBuilder();
    // Adapter to convert long values to date types
    gsonBuilder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {
        public Date deserialize(JsonElement jsonElement, Type typeOfObj, JsonDeserializationContext context)
               throws JsonParseException {
                   //Converting milliseconds to current Date. (instead of 1970)
                return new Date(jsonElement.getAsLong() * 1000);
            }
        });
    Gson gson = gsonBuilder.setPrettyPrinting().create();

0

У мене така ж проблема , коли я спробував десеріалізацію DateTime поля з Rest клієнтом з Android анотацій бібліотеки. Як рішення я створив власний GsonHttpMessageConverter

public class CustomGsonHttpMessageConverter extends GsonHttpMessageConverter {

    public CustomGsonHttpMessageConverter() {
        // Creates the json object which will manage the information received
        GsonBuilder builder = new GsonBuilder();

        // Register an adapter to manage the date types as long values
        builder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {
            public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
                return new Date(json.getAsJsonPrimitive().getAsLong());
            }
        });

        setGson(builder.create());
    }
}

і визначити його в клієнті відпочинку

@Rest(rootUrl = "http://192.168.1.1:8080", converters = {CustomGsonHttpMessageConverter.class})
public interface RestClient extends RestClientErrorHandling {
...

Сподіваюся, це буде корисно


0

З якоїсь причини у мене були помилки компіляції в Intellij із зазначеним вище кодом із використанням анонімного класу; лямбда працювала у мене:

private static Gson buildGson(){
    // Deserialize longs as Dates
    final JsonDeserializer<Date> dateDeserializer = (json, type, context) -> json == null ? null : new Date(json.getAsLong());
    return new GsonBuilder().registerTypeAdapter(Date.class, dateDeserializer).create();
}
Використовуючи наш веб-сайт, ви визнаєте, що прочитали та зрозуміли наші Політику щодо файлів cookie та Політику конфіденційності.
Licensed under cc by-sa 3.0 with attribution required.