Java Date to UTC using gson

后端 未结 4 458
死守一世寂寞
死守一世寂寞 2020-12-05 00:04

I can\'t seem to get gson to convert a Date to UTC time in java.... Here is my code...

Gson gson = new GsonBuilder().setDateFormat(\"yyyy-MM-dd\'T\'HH:mm:ss.         


        
4条回答
  •  一向
    一向 (楼主)
    2020-12-05 00:32

    I adapted the marked solution and parametrized the DateFormat:

    import com.google.gson.JsonDeserializationContext;
    import com.google.gson.JsonDeserializer;
    import com.google.gson.JsonElement;
    import com.google.gson.JsonParseException;
    import com.google.gson.JsonPrimitive;
    import com.google.gson.JsonSerializationContext;
    import com.google.gson.JsonSerializer;
    
    import java.lang.reflect.Type;
    import java.text.DateFormat;
    import java.text.ParseException;
    import java.util.Date;
    
    public class GsonDateFormatAdapter implements JsonSerializer, JsonDeserializer {
    
        private final DateFormat dateFormat;
    
        public GsonDateFormatAdapter(DateFormat dateFormat) {
            this.dateFormat = dateFormat;
        }
    
        @Override
        public synchronized JsonElement serialize(Date date, Type type, JsonSerializationContext jsonSerializationContext) {
            return new JsonPrimitive(dateFormat.format(date));
        }
    
        @Override
        public synchronized Date deserialize(JsonElement jsonElement, Type type,JsonDeserializationContext jsonDeserializationContext) {
            try {
                return dateFormat.parse(jsonElement.getAsString());
            } catch (ParseException e) {
                throw new JsonParseException(e);
            }
        }
    }
    

提交回复
热议问题