Skip to content

Suggest adding custom features to Gson for LocalDateTime and LocalDate #18

Closed

Description

@marklee1972

Since use com.google.gson.Gson to parse the json of Etherscan's api response.
However the error will appear:
io.api.etherscan.error.ParseException: Unable to make field private final java.time.LocalDate java.time.LocalDateTime.date accessible: module java.base does not "opens java.time" to unnamed module @38d8f54a

The reason is at:
io.api.etherscan.core.impl.BasicProvider

Line 47:
this.gson = new Gson();

I change the below code to fix this issuse:

this.gson = new GsonBuilder()
                .registerTypeAdapter(LocalDateTime.class, (JsonSerializer<LocalDateTime>) (src, typeOfSrc, context) -> new JsonPrimitive(src.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))))
                .registerTypeAdapter(LocalDate.class, (JsonSerializer<LocalDate>) (src, typeOfSrc, context) -> new JsonPrimitive(src.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"))))
                .registerTypeAdapter(LocalDateTime.class, (JsonDeserializer<LocalDateTime>) (json, type, jsonDeserializationContext) -> {
                    String datetime = json.getAsJsonPrimitive().getAsString();
                    return LocalDateTime.parse(datetime, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                }).registerTypeAdapter(LocalDate.class, (JsonDeserializer<LocalDate>) (json, type, jsonDeserializationContext) -> {
                    String datetime = json.getAsJsonPrimitive().getAsString();
                    return LocalDate.parse(datetime, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
                }).create();

Maybe the best way is either update the source code or supply a custom features.

Activity

  1. GoodforGod commented on Mar 8, 2022

    @GoodforGod
    Owner

    Hello, thanks for the issue, I will look into it and thanks for the details and provided code!

  2. GoodforGod commented on Mar 8, 2022

    @GoodforGod
    Owner

    Can you please tell what is endpoint/method library fails and what JDK version you used?

  3. marklee1972 commented on Mar 8, 2022

    @marklee1972
    Author

    Can you please tell what is endpoint/method library fails and what JDK version you used?

    Yep
    JDK JavaSE-1.8(jdk17.0.1)
    Both MAINNET and ROPSTEN are the same error.
    When querying for a transaction, it happens.

    List tx = api.account().txs(ADDRESS);

  4. GoodforGod commented on Mar 8, 2022

    @GoodforGod
    Owner

    Thanks for the info! Investigating and will release fix soon as possible

  5. added this to the v1.2.1 milestone on Mar 8, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

bugSomething isn't workingenhancementNew feature or request

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions