Home > other >  Error when trying to convert Java object to JSON string using GSON
Error when trying to convert Java object to JSON string using GSON

Time:12-31

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 [email protected]/com.google.gson.internal.ConstructorConstructor.newDefaultConstructor(ConstructorConstructor.java:101) at [email protected]/com.google.gson.internal.ConstructorConstructor.get(ConstructorConstructor.java:83) at [email protected]/com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.create(ReflectiveTypeAdapterFactory.java:99) at [email protected]/com.google.gson.Gson.getAdapter(Gson.java:423) at [email protected]/com.google.gson.Gson.toJson(Gson.java:661) at [email protected]/com.google.gson.Gson.toJson(Gson.java:648) at [email protected]/com.google.gson.Gson.toJson(Gson.java:603) at [email protected]/com.google.gson.Gson.toJson(Gson.java:583) at IAssessment/application.AddData.main(AddData.java:23) - this is line String object = json.toJson(mp);

Pls help

CodePudding user response:

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;
  • Related