简体   繁体   中英

Error when trying to convert Java object to JSON string using GSON

I have an object MobilePhone with fields (String brand and name, int ram and rom) that I want to convert to a Json string. I try doing so like this

         public static void main(String[] args){
         MobilePhone mp = new MobilePhone();    
         mp.setBrand("iPhone");
         mp.setName("X");
         mp.setRam(4);
         mp.setRom(1);
         
         Gson json = new Gson();
         String object = json.toJson(mp);
            System.out.println(object);     
     }

I get the following errors:

Exception in thread "main" java.lang.reflect.InaccessibleObjectException: Unable to make public (package name).MobilePhone() accessible: module (project name) does not "exports (package name)" to module gson at java.base/java.lang.reflect.AccessibleObject.checkCanSetAccessible(AccessibleObject.java:349) at java.base/java.lang.reflect.AccessibleObject.checkCanSetAccessible(AccessibleObject.java:289) at java.base/java.lang.reflect.Constructor.checkCanSetAccessible(Constructor.java:189) at java.base/java.lang.reflect.Constructor.setAccessible(Constructor.java:182) at gson@2.8.2/com.google.gson.internal.ConstructorConstructor.newDefaultConstructor(ConstructorConstru ctor.java:101) at gson@2.8.2/com.google.gson.internal.ConstructorConstructor.get(ConstructorConstructor.java:83) at gson@2.8.2/com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.create(ReflectiveTypeAdapterFactory.java:99) at gson@2.8.2/com.google.gson.Gson.getAdapter(Gson.java:423) at gson@2.8.2/com.google.gson.Gson.toJson(Gson.java:661) at gson@2.8.2/com.google.gson.Gson.toJson(Gson.java:648) at gson@2.8.2/com.google.gson.Gson.toJson(Gson.java:603) at gson@2.8.2/com.google.Z6 716608096280862A88268DB0DE397CDZ.Gson.toJson(Gson.java:583) at IAssessment/application.AddData.main(AddData.java:23) - this is line String object = json.toJson(mp);

Pls help

As the error indicates, the module containing the MobilePhone class does not export the package containing MobilePhone , so it is not visible outside of its own module. (Or if it is exported, it is only exported to some modules other than gson.) In general this means that you must add an exports directive to the module descriptor file, like so:

exports <pkg-name> to gson;

But since gson uses reflection extensively, probably you need to go a step further and provide private and reflective access of the package to gson. To do this, add an opens directive to the module descriptor file:

opens <pkg-name> to gson;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM