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
1 2 3 4 5 | var json = """ {"first":"Mickey", "last":"Mouse", "birth_year":1928} """; |
For example before records, I would write:
1 2 3 4 5 6 7 | 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:
1 2 3 | record Name(String first, String last, @SerializedName("birth_year") int birthYear) { } |
The parsing code remains the same
1 2 3 | var gson = new Gson(); var name = gson.fromJson(json, Name.class); System.out.println(name); |