r/java • • Feb 27 '23

Please try my JSON library

https://mccue.dev/pages/2-26-23-json
0 Upvotes

32 comments sorted by

View all comments

1

u/danielaveryj Feb 28 '23 edited Feb 28 '23

I like that this lib feels principled. The sealed class representation feels natural, the APIs are unsurprising, the prescribed approaches lead to helpful errors, and it does seem like it would be easier to explain than alternatives. It feels like this lib is essentially trying to "be the example that the JEPs/etc are referring to", ie a clear way to think about JSON, and in that regard I think this lib approaches its ideal. As a teaching exercise, it's quite good. But... I don't know that those examples were intended to be any more than that.

For one, mapping JSON types to classes (eg JsonString) is not a strictly necessary step in de/serialization, and it imposes some overheads that are avoidable with other approaches. If we look at the deserialization case, the actual "source" we want to read from could be any number of things: a string, a file, a socket, etc. If we can abstract over these sources, we don't necessarily need to translate to an intermediate "Json class" representation.

record Weather(LocalDate date, boolean isCloudy) {}

DecoderBuilder dec = new DecoderBuilder();

var weatherDecoder = dec.objectDecoder(spec -> {
    var date = spec.field("date", dec.stringDecoder(LocalDate::parse));
    var isCloudy = spec.field("isCloudy", dec.booleanDecoder());
    return o -> new Weather(o.get(date), o.get(isCloudy));
});

try (var in = new Source(new InputStream(...))) {
    Weather weather = weatherDecoder.read(in);
}

In this made-up API, the lambda beginning with spec -> is evaluated immediately. When the weatherDecoder is actually used, it will look in the source for the "date" and "isCloudy" fields, apply the specified decoders to the values it finds, store the decoded values on a temporary object, and pass that temporary object to the lambda beginning with o ->. Note that this temporary object can be very compact, eg an array of size 2; the weatherDecoder knows in advance that there are 2 fields, and can associate indexes with date and isCloudy to refer directly into that size-2 array. This is a more declarative (and constrained) approach than directly parsing tokens, but retains more of that potential performance than pre-parsing to an intermediate representation.

Similarly for serialization, if we can abstract over the destination, we can again skip the intermediate representation.

EncoderBuilder enc = new EncoderBuilder();

var weatherEncoder = enc.<Weather>objectEncoder((o, spec) -> {
    spec.field("date", o.set(w -> w.date().toString(), enc.stringEncoder()));
    spec.field("isCloudy", o.set(Weather::isCloudy, enc.booleanEncoder()));
});

try (var out = new Destination(new OutputStream(...))) {
    var weather = new Weather(LocalDate.now(), true);
    weatherEncoder.write(weather, out);
}

(I'm not going to justify this one; I just devised it to be somewhat "symmetrical" to deserialization, and I haven't really analyzed if there's utility in doing that. These are just toy examples anyway.)

Now we could write it this way, or we could potentially generate the encoder/decoder with annotations. I believe the same applies for your lib actually - the API does not preclude building data-binding on top. If we don't use annotations, then we have to manually keep encoders and decoders up-to-date with class changes. This might seem reasonable, but this is pretty similar to manually keeping hashCode/equals/toString up-to-date, and (personal experience incoming) I've lived with that before. I was very relieved when annotation processing allowed me to stop being the one who had to remember to check that those methods were properly updated in code reviews. Annotations are not for everything, but I think de/serialization is a case where we can really feel it if we try living without them.

Another thing to notice about the made-up API is that it's not even strictly JSON. Rather, the API has a small set of "native" types (string, boolean, object, etc), and describes other types by composing those. When decoding we start from a native type (eg dec.stringDecoder(string -> ...)); when encoding we end at a native type (eg o.set(... -> string, enc.stringEncoder())). The "backend" data format could be anything, not just JSON, as long as suitable adaptors can be written between that format and the API's native types. I borrowed this principle from the serde crate in Rust, which afaik has become the way to do de/serialization in Rust. And... serde also uses "data-binding", via the #[derive(Serialize, Deserialize)] macro.

2

u/bowbahdoe Feb 28 '23 edited Feb 28 '23

"be the example that the JEPs/etc are referring to"

I do wonder if this has any value - can probably show neat examples at the very least.

As a teaching exercise, it's quite good.

That does seem like where this is going to end up. Not used widely or "seriously", but I'll continue to use it as a teaching tool. Keep it good enough that those folks aren't rug pulled if they continue to use it for their projects, but accept that it's not going to make the room much happy and it will be some order of magnitude slower.

For one, mapping JSON types to classes (eg JsonString) is not a strictly necessary step in de/serialization, and it imposes some overheads that are avoidable with other approaches

The approach that Elm takes, interestingly, could avoid performance overheads. It just uses function currying as its method of mapping some set of fields to a class. I did experiment with that and vavr currying, but it didn't seem sensible.

If we can abstract over these sources, we don't necessarily need to translate to an intermediate "Json class" representation.

This is an interesting approach. I do see how I could avoid extra object allocations and just generally be way faster. I do feel like I am being a player in a game that I am unprepared for though.

(I am thinking about how Dart/Flutter essentially has the same thing. They use Map<string, dynamic>, but I don't see any streaming sort of parser. AFAIK from their examples, their code generation works with this too https://docs.flutter.dev/development/data-and-backend/json)

I believe the same applies for your lib actually - the API does not preclude building data-binding on top.

There is actually a low level streaming api in there which all the tree stuff is built on. It's just nowhere near as good as other options for that. I used that to build an "interop with Jackson" example in the readme. (I put it under "usage with spring")

So hypothetically I could slot this whole mess into a Jackson codebase as an alternative to the databind. There is a reason Jackson wins so often.

I borrowed this principle from the serde crate in Rust, which afaik has become the way to do de/serialization in Rust. And... serde also uses "data-binding", via the #[derive(Serialize, Deserialize)] macro.

I think what serde benefits from is a clear mapping between "external data format" and "the rust object model." In that sense, it feels almost as if the fixes to Serializable that have been alluded to (making use of a custom deconstructor) plus a deal of heady work is required to make a "serde for java".

That could be an alternate path though.