Here is my code example
public record Person(String firstName, String lastName) {}
@Test
void test() {
String json =
"""
{
"firstName": "John",
"lastName": "Doe"
}
""";
Person person = new Gson().fromJson(json, Person.class);
assertEquals("John", person.firstName);
}
Here is an exception I get:
java.lang.AssertionError: AssertionError (GSON 2.8.9): java.lang.IllegalAccessException: Can not set final java.lang.String field com.test.GsonTest$Person.firstName to java.lang.String
Is there any way to deserialize JSON to java record using Gson?
Gson 2.10 supports Java 16+ records: https://github.com/google/gson/releases
The previously linked https://github.com/google/gson/issues/1794 has a number of workarounds in thread if you can't upgrade.