1

I am converting an object to JSON using com.google.code.gson:gson:2.2.4 library by using code:

String json = new GsonBuilder().excludeFieldsWithModifiers(Modifier.PROTECTED).create().toJson(object);

And in the JSON string "serialVersionUID" is added automatically with Long value even if it is not in a model class. I just want to remove serialVersionUID from JSON.

Lyubomyr Shaydariv
  • 20,327
  • 12
  • 64
  • 105
Rajat Mehra
  • 1,462
  • 14
  • 19

2 Answers2

0

I found this answer. Basically, the serialVersionUID is added by InstantRun, disabling InstantRun solved the issue for me.

user2880229
  • 151
  • 8
0

One way to get around this is to use GsonBuilder.excludeFieldsWithoutExposeAnnotation then use the @Expose annotation to explicitly mark what is or isn't (de)serialized.

public class SomeClass {
    private int field1 = 2;
    @Expose private int field2 = 6;
    @Expose @SerializedName ("foo") private int field3 = 12;
}

gives you {"field2":6, "foo":12}. The field field1 is excluded because it isn't annotated with @Expose.

Personally, I always use the GsonBuilder.excludeFieldsWithoutExposeAnnotation because it filters out any generated fields (like the Instant Run comment above). If you didn't annotate it with @Expose, it won't be serialized/deserialized.

Another way is to declare the field as transient.

copolii
  • 14,208
  • 10
  • 51
  • 80