Search code examples
javamavengson

gson cannot be resolved to a module error in module-info.java


I've created a maven project in VScode and added GSON to my pom.xml:

        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.10.1</version>
        </dependency>

I'm using Java 17 and modules for the first time.

I've added "requires gson;" to my module-info.java but it reports "gson cannot be resolved to a module" The Maven dependencies are showing the gson:2.10.1 library and I see it has been downloaded in the .m2/respository folder.

My module-info.java:


module mypackage {
    // needed for JavaFX
    requires javafx.controls;
    requires javafx.fxml;
    //requires javafx.swing;
    requires transitive javafx.graphics;

    // needed for HTTP
    requires unirest.java;

    // needed for JSON
    requires gson;
    requires java.sql;

    // needed for JavaFX
    opens mypackage to javafx.fxml;

    exports mypackage;
}

Obviously in the class where I import Gson, GsonBuilder, etc it fails with "The type com.google.gson.Gson is not accessible".

Any ideas? Go gentle I'm not a programmer by trade.


Solution

  • The module name of Gson is com.google.gson (see also the README or the Javadoc). Therefore you should use:

    requires com.google.gson;
    

    But most likely you will also have to open your packages to Gson because it uses reflection to access the fields of your classes:

    opens mypackage to com.google.gson;
    

    (Also for the recent Gson versions you don't have to add requires java.sql anymore.)