Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Failed to serialize object (using Room DB) to json string using Gson

I have a class Item (see below) in which I have used some Room db annotations. It also has a nested class named ItemInfo. Both of these classes have an empty constructor.

The problem is that when I try to serialize an object of Item class, app crashes with the following error:

E/AndroidRuntime: FATAL EXCEPTION: main
              Process: com.android.carrymates, PID: 18526
              java.lang.SecurityException: Can not make a java.lang.reflect.Method constructor accessible
                  at java.lang.reflect.AccessibleObject.setAccessible0(AccessibleObject.java:133)
                  at java.lang.reflect.AccessibleObject.setAccessible(AccessibleObject.java:119)
                  at com.google.gson.internal.reflect.PreJava9ReflectionAccessor.makeAccessible(PreJava9ReflectionAccessor.java:31)
                  at com.google.gson.internal.ConstructorConstructor.newDefaultConstructor(ConstructorConstructor.java:103)
                  at com.google.gson.internal.ConstructorConstructor.get(ConstructorConstructor.java:85)
                  at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.create(ReflectiveTypeAdapterFactory.java:101)
                  at com.google.gson.Gson.getAdapter(Gson.java:458)
                  at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.createBoundField(ReflectiveTypeAdapterFactory.java:117)
                  at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.getBoundFields(ReflectiveTypeAdapterFactory.java:166)
                  at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.create(ReflectiveTypeAdapterFactory.java:102)
                  at com.google.gson.Gson.getAdapter(Gson.java:458)
                  at com.google.gson.internal.bind.ArrayTypeAdapter$1.create(ArrayTypeAdapter.java:48)
                  at com.google.gson.Gson.getAdapter(Gson.java:458)
                  at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.createBoundField(ReflectiveTypeAdapterFactory.java:117)
                  at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.getBoundFields(ReflectiveTypeAdapterFactory.java:166)
                  at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.create(ReflectiveTypeAdapterFactory.java:102)
                  at com.google.gson.Gson.getAdapter(Gson.java:458)
                  at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.createBoundField(ReflectiveTypeAdapterFactory.java:117)
                  at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.getBoundFields(ReflectiveTypeAdapterFactory.java:166)
                  at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.create(ReflectiveTypeAdapterFactory.java:102)
                  at com.google.gson.Gson.getAdapter(Gson.java:458)
                  at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.createBoundField(ReflectiveTypeAdapterFactory.java:117)
                  at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.getBoundFields(ReflectiveTypeAdapterFactory.java:166)
                  at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.create(ReflectiveTypeAdapterFactory.java:102)
                  at com.google.gson.Gson.getAdapter(Gson.java:458)
                  at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.createBoundField(ReflectiveTypeAdapterFactory.java:117)
                  at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.getBoundFields(ReflectiveTypeAdapterFactory.java:166)
                  at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.create(ReflectiveTypeAdapterFactory.java:102)
                  at com.google.gson.Gson.getAdapter(Gson.java:458)
                  at com.google.gson.Gson.toJson(Gson.java:696)
                  at com.google.gson.Gson.toJson(Gson.java:683)
                  at com.google.gson.Gson.toJson(Gson.java:638)
                  at com.google.gson.Gson.toJson(Gson.java:618)
                  ... more log (irrelevant to question asked)

Item.java

@Entity(tableName = "items", indices = {@Index(value = {"id"}, unique = true), @Index(value = {"owner", "type"})})
public class Item {

    @PrimaryKey
    @NonNull
    String id="";

   //...rest fields are int, boolean and String only

    @Embedded
    ItemInfo itemInfo; // see ItemInfo


    public Item() {

   }


    // ...getters and setters

    @IgnoreExtraProperties
    public static class ItemInfo {

        //...fields are int, boolean and String only

        public ItemInfo() {

        }

        //...getters and setters
    }
}

My guess is that Room DB annotations are adding at least one object of type java.lang.reflect.Method which Gson is unable to serialize.

Below is the code I am using to serialize Item object to json string, where item is a object of class Item with non-null values of fields of type String and ItemInfo.

Gson gson = new Gson();
String result = gson.toJson(item); // crash begins from here

How do I address this problem? I expect at least a workaround solution.

like image 689
krhitesh Avatar asked Nov 08 '22 02:11

krhitesh


1 Answers

Disclaimer:

I'm not aware of what RoomDB does with @Entity classes (though it looks like RoomDB uses subclasses rather than classes written by you).

Also I run the test on JVM

But I can suggest you to use @Expose:

public class GsonTest {

  private static class SampleModel {
    @Expose
    private int i;

    private Method method;

    @Expose
    private Nested nested = new Nested();
  }

  private static class Nested {
    @Expose
    private String a = "my string";
  }

  @Test
  public void failsWithMethodField() throws Exception {
    assertThrows(Exception.class, () -> {
      SampleModel sampleModel = new SampleModel();
      sampleModel.i = 10;
      sampleModel.method = Object.class.getDeclaredMethod("equals", Object.class);
      Gson gson = new Gson();
      gson.toJson(sampleModel);
    });
  }

  @Test
  public void withExposedDoesNotFail() {
    assertDoesNotThrow(() -> {
      SampleModel sampleModel = new SampleModel();
      sampleModel.method = Object.class.getDeclaredMethod("equals", Object.class);
      Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
      String json = gson.toJson(sampleModel);
      System.out.println(json); // {"i":0,"nested":{"a":"my string"}}
    });
  }
}

The essential part is to configure Gson with excludeFieldsWithoutExposeAnnotation option:

Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();

Then mark all fields that should be used when serializing and deserializing with @Expose annotation.

like image 57
Denis Zavedeev Avatar answered Nov 13 '22 19:11

Denis Zavedeev