简体   繁体   中英

Deserialize JSON to java record using Gson

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM