Is there a standard implementation for a GSON Joda Time serialiser?

后端 未结 6 1866
梦毁少年i
梦毁少年i 2020-12-25 11:27

I\'m using GSON to serialise some object graphs to JSON. These objects graphs use Joda Time entities (DateTime, LocalTime etc).

The top Go

相关标签:
6条回答
  • 2020-12-25 12:01

    register a TypeAdapter with GSON to wrap the use of a Joda preconfigured Formatters, see http://www.joda.org/joda-time/apidocs/org/joda/time/format/ISODateTimeFormat.html

    import java.lang.reflect.Type;
    import com.google.gson.Gson;
    import com.google.gson.GsonBuilder;
    import com.google.gson.JsonElement;
    import com.google.gson.JsonPrimitive;
    import com.google.gson.JsonSerializationContext;
    import com.google.gson.JsonSerializer;
    import java.lang.reflect.Type;
    import org.joda.time.DateTime;
    import org.joda.time.format.ISODateTimeFormat;
    
    public class JodaDateTimeWithGson {
    
        public static void main(String[] args) {
            Gson gson = new GsonBuilder()
                .registerTypeAdapter(DateTime.class, new JsonSerializer<DateTime>(){
                    @Override
                    public JsonElement serialize(DateTime json, Type typeOfSrc, JsonSerializationContext context) {
                        return new JsonPrimitive(ISODateTimeFormat.dateTime().print(json));
                    }
                })
                .create()
                ;
    
            // Outputs ["20160222T15:58:33.218Z",42,"String"]
            System.out.println(gson.toJson(new Object[] {DateTime.now(), 42, "String"}));
        }
    }
    
    0 讨论(0)
  • 2020-12-25 12:02

    replicate that snippet, a lot of people use different date string formatting thus confusing any library creation.

    0 讨论(0)
  • 2020-12-25 12:05

    I used the answers above to do a little helper that will handle both serialization and deserialization for model objects containing DateTime variables.

        public static Gson gsonDateTime() {
        Gson gson = new GsonBuilder()
                .registerTypeAdapter(DateTime.class, new JsonSerializer<DateTime>() {
                    @Override
                    public JsonElement serialize(DateTime json, Type typeOfSrc, JsonSerializationContext context) {
                        return new JsonPrimitive(ISODateTimeFormat.dateTime().print(json));
                    }
                })
                .registerTypeAdapter(DateTime.class, new JsonDeserializer<DateTime>() {
                    @Override
                    public DateTime deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
                        DateTime dt = ISODateTimeFormat.dateTime().parseDateTime(json.getAsString());
                        return dt;
                    }
                })
                .create();
        return gson;
    }
    
    0 讨论(0)
  • 2020-12-25 12:13

    I am using next in my project

    public final class DateTimeDeserializer implements JsonDeserializer<DateTime>, JsonSerializer<DateTime>
    {
       static final org.joda.time.format.DateTimeFormatter DATE_TIME_FORMATTER =
          ISODateTimeFormat.dateTime().withZone(DateTimeZone.UTC);
    
       @Override
       public DateTime deserialize(final JsonElement je, final Type type,
                               final JsonDeserializationContext jdc) throws JsonParseException
       {
          return je.getAsString().length() == 0 ? null : DATE_TIME_FORMATTER.parseDateTime(dateAsString);
       }
    
       @Override
       public JsonElement serialize(final DateTime src, final Type typeOfSrc,
                                    final JsonSerializationContext context)
       {
          return new JsonPrimitive(src == null ? StringUtils.EMPTY :DATE_TIME_FORMATTER.print(src)); 
       }
    }
    
    0 讨论(0)
  • 2020-12-25 12:14

    It seems to me quite normal that you don't have this kind of library available.

    It might look simple at first glance, but the risk is that you end up with a lot of dependencies (some at compile time, some at runtime), and it would not be easy to make sure you don't create unwanted dependencies.

    For your case, this should be ok, as I think this is only a runtime dependency (Then a project using the serializerLib should not need JODA lib if JODA is not used). But for some other case, this could become ugly.

    0 讨论(0)
  • 2020-12-25 12:25

    I've decided to roll my own open source one - you can find it here:

    https://github.com/gkopff/gson-jodatime-serialisers

    Here's the Maven details (check central for the latest version):

    <dependency>
      <groupId>com.fatboyindustrial.gson-jodatime-serialisers</groupId>
      <artifactId>gson-jodatime-serialisers</artifactId>
      <version>1.6.0</version>
    </dependency>
    

    And here's a quick example of how you drive it:

    Gson gson = Converters.registerDateTime(new GsonBuilder()).create();
    SomeContainerObject original = new SomeContainerObject(new DateTime());
    
    String json = gson.toJson(original);
    SomeContainerObject reconstituted = gson.fromJson(json, SomeContainerObject.class);
    
    0 讨论(0)
提交回复
热议问题