jdereg / json-io

Convert Java to JSON. Convert JSON to Java. Pretty print JSON. Java JSON serializer. Deep copy Java object graphs.
Apache License 2.0
331 stars 115 forks source link

Deserialization of records doesn't work in Java15 #151

Closed reuschling closed 2 years ago

reuschling commented 3 years ago

If you want to deserialize a record, you get an IllegalAccessException: Can not set final ... field.

I assume the problem will exist also in the new Java16 which comes out next week, where records won't be a preview feature anymore.

Example code:

    public static record TestRecord(String str, boolean bool)
    {

    }

...

        TestRecord rec = new TestRecord("check", false);

        String strJson = JsonWriter.objectToJson(rec);
        System.out.println(strJson);

        TestRecord clone = (TestRecord) JsonReader.jsonToJava(strJson);
        System.out.println(clone);

Gson also has this issue: https://github.com/google/gson/issues/1794. According this, the solution would be to use the constructor in favour of setting the final fields via reflection.

jdereg commented 2 years ago

json-io has the assign instantiator customization that lets you write the code that creates the object, which allows you to set up the object in regular code - your code is called when the troubled class is encountered. This is dicussed in the user-guide, linked here: https://github.com/jdereg/json-io/blob/master/user-guide.md under the Customization section. Also, recent changes have been added to support JDK's through 17.