gkopff / gson-javatime-serialisers

A set of GSON serialiser/deserialisers for dealing with Java 8 java.time entities.
MIT License
87 stars 19 forks source link

YearMonth parser would be beneficial #26

Open nbali opened 5 years ago

gkopff commented 5 years ago

@nbali would you like to contribute a PR?

nbali commented 5 years ago

I have no time to do it properly with docs, tests and stuff nowadays, but here is the pure code itself for anyone willing to finish it:

import java.lang.reflect.Type;
import java.time.YearMonth;

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 com.google.gson.reflect.TypeToken;

...

    private static class YearMonthConverter implements JsonSerializer<YearMonth>, JsonDeserializer<YearMonth> {

        private static final Type TYPE = TypeToken.get(YearMonth.class).getType();

        @Override
        public JsonElement serialize(YearMonth src, Type typeOfSrc, JsonSerializationContext context) {
            return new JsonPrimitive(src.toString());
        }

        @Override
        public YearMonth deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
            return YearMonth.parse(json.getAsString());
        }
    }