Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java GSON deserializer LocalDate

Tags:

java

gson

I have a problem trying to deserialize a gson LocalDate. I have the next 2 adaptors:

 public class LocalDateSerializer implements JsonSerializer < LocalDate > {
    private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("d-MMM-yyyy");

    @Override
    public JsonElement serialize(LocalDate localDate, Type srcType, JsonSerializationContext context) {
        return new JsonPrimitive(formatter.format(localDate));
    }
}

and

public class LocalDateDeserializer implements JsonDeserializer < LocalDate > {
    @Override
    public LocalDate deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
            throws JsonParseException {
        return LocalDate.parse(json.getAsString(),
                DateTimeFormatter.ofPattern("d-MMM-yyyy").withLocale(Locale.ENGLISH));
    }
}

I try to make a simple Serialization of an object "Task" which have a field starttime of LocalDate type.

   GsonBuilder gsonBuilder = new GsonBuilder();
        gsonBuilder.registerTypeAdapter(LocalDate.class, new LocalDateSerializer());
        gsonBuilder.registerTypeAdapter(LocalDate.class, new LocalDateDeserializer());
        Gson gson = gsonBuilder.setPrettyPrinting().create();

        LocalDate now=LocalDate.now();
        Task task=new Task();
        task.setID(1);
        task.setDuration(2);
        task.setID_Proiect(1);
        task.setStarttime(now);

        JSONObject json=new JSONObject(task);
        String aux1=gson.toJson(json);

        System.out.println(aux1);
        Task t2=gson.fromJson(aux1,Task.class);

I receive the error

Failed making field 'java.time.LocalDateTime#date' accessible; either change its visibility or write a custom TypeAdapter for its declaring type

Can you tell me what is wrong with this code? I know it is probably a noobie question but i rly need help to improve my skills. Ty

like image 943
Hudini Avatar asked Aug 23 '26 12:08

Hudini


1 Answers

I had the same issue with deserializing java.time.Instant with gson during java upgrade 11 to 17, Please refer the gson documentation sheds light on why it happens: https://github.com/google/gson/blob/main/UserGuide.md#gsons-expose

Solution: create Gson by using- new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create()

like image 118
Praveen Kumar Verma Avatar answered Aug 25 '26 01:08

Praveen Kumar Verma



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!