Towards a JSON API for the JDK
forax at univ-mlv.fr
forax at univ-mlv.fr
Mon May 19 14:54:46 UTC 2025
----- Original Message -----
> From: "cay horstmann" <cay.horstmann at gmail.com>
> To: "Remi Forax" <forax at univ-mlv.fr>
> Cc: "core-libs-dev" <core-libs-dev at openjdk.org>
> Sent: Monday, May 19, 2025 4:12:55 PM
> Subject: Re: Towards a JSON API for the JDK
> Il 19/05/25 10:13, Remi Forax ha scritto:
>>> If only there was some deconstruction magic that approximates the JavaScript
>>> code
>>>
>>> const doc = { name: "John", age: 30 }
>>> const { name, age } = doc
>>
>> We already have that, it's called a record :)
>>
>> Basically, you are advocating for a mapping JsonObject <--> record.
>>
>> [...]
>>
>>>
>>> Cheers,
>>>
>>> Cay
>>>
>>
>> Here is a simple JsonObject mapper using java.util.json types.
>> https://github.com/forax/json-object-mapper
>
> That's interesting, but I don't think it works as a solution to read generic
> JSON. I have to deal with much JSON that is at best semi-structured. And
> anyway, databinding is is excluded from the scope of the core Java JSON API.
If the mapping is driven by the record definition then mapping and matching are mostly equivalent,
mapping throws exceptions when something goes wrong while matching returns something saying no-match.
Here is an example,
record Person(String name, int age) {}
var recordMapper = RecordMapper.of(MethodHandles.lookup());
JsonObject json = ...
if (recordMapper.match(json, Person.class) instanceof Person(String name, int age)) {
// can use name and age here
}
see https://github.com/forax/json-object-mapper/blob/master/src/test/java/json/RecordMapperTest.java#L40
[...]
>
> At first I thought the pattern matching version would be worse, but I admit that
> the structural safety is appealing.
I agree.
>
> Cheers,
>
> Cay
Rémi
More information about the core-libs-dev
mailing list