gson supports records

I like using records in Java and getting rid of the boilerplate on my immutable objects. I also like using gson (google’s serialization/deserialization library) for my lightweight JSON needs. All I need is an annotation to use a different field type. (For complex parsing I use Jackson)

Suppose I want parse this

var json = """
   {"first":"Mickey",
	"last":"Mouse",
	"birth_year":1928}
	""";

For example before records, I would write:

class Name {
	 private String first;
	 private String last;
     @SerializedName("birth_year") int birthYear;

     // boilerplate methods
}

I needed to use my IDE to generate a constructor, getters, and a toString(). And additionally, equals/hashCode if needed for that class.

In Java 17, I switched to records. I didn’t realize I could use them with gson annotations until recently. Turns out all I need to write is:

record Name(String first, 
   String last, 
   @SerializedName("birth_year") int birthYear) { }

The parsing code remains the same

var gson = new Gson();
var name = gson.fromJson(json, Name.class);
System.out.println(name);

Leave a Reply

Your email address will not be published. Required fields are marked *