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

12

u/rzwitserloot Feb 27 '23 edited Feb 27 '23

About this library:

I think it's inferior to both a better designed API to deal with basic JSON, or to the more commonly taken route out there, which is marshalling (where you define a type and then tell a library: Here's some JSON, here's a java type, you figure out how to ram this square peg in the round hole please).

It's neat how the new pattern match stuff in JDK19+ is making this API design not completely disastrous, but you can do better. The key point you're presumably missing is somewhat similar to the same trick Map's .getOrDefault uses:

JSON is very 'weakly' typed. There's no real way to know a JSON value is a date, because JSON doesn't have a date type. There's no way to know if a numeric value is intended for API consumption purposes to be an int or a long or a timestamp or who knows what.

Hence, it's a great idea for the consumer of the JSON (the Java code) to tell the parsing system what you want. Instead of having the parsing system give you a JSON object and then having to manipulate that into what you want.

It's similar to how map has .getOrDefault(k, defaultValue) which is the 'right answer' to the more like-your-stuff library idea of having a .get2(k) method that returns an Optional, which you then use to manipulate what you get into what you want.

In other words, your code: JsonDecoder.field(json, "canSpeak", JsonDecoder::boolean_) is needlessly convoluted. It can simply be:

return new Muppet(json.getString("name"), json.getBoolean("canSpeak"));

There, knocked your 9-liner down to a 1-liner, which is hardly more complicated than any one line in your example.

You have to define a boatload of methods, and for simplicity you may want to go with json.get("name").asString(), especially as that makes it easy to offer an overload where you pass a default value to the asString() method that is used if the name field doesn't exist. You can keep the decoder style but only for the rare cases where the transformation you want isn't obvious (boolean, int, double, String, LocalDate, and even List<String> - these are obvious things). However, 'lots of methods here', especially if they have a common prefix, is not a burden on API consumers. Whereas having to type all that out every time I simply want to read a string from some JSON is quite burdensome.

For bonus points, given that a lot of JSON is nested, imagine as input:

{"movies": [
  {
    "director": {"name": "Joe", "DOB": "1970-01-01"},
    "name": "Awesome movie"
  }
]
}

fairly common, no? Imagine you can read that with:

JSON json = JSON.parse(that);
for (JSON m : json.get("movies").asList()) {
  String directorName = m.get("director").get("name").asString("Alan Smithee");
  LocalDate directorDob = m.get("director").get("DOB").asDate();
}

I think it's a slam dunk to state that the vast majority of JSON out there comes in two flavours:

  • It follows a highly precise specification (think WSDL), and thus it is quite likely the right way to parse it is to define a java class that mirrors the spec and then hand a marshalling library the JSON and a classref to your type and have the library make instances for you.

  • It's a lot more laissez faire, with a spec that is littered with 'if value X is missing, assume this default', and 'This value can either be a list, or, if it's a simple single item, then there's no list and we just have the item directly as value, or even nothing at all if there are no values for this list' and such. In which case this asTypeYouWant(defaultValueIfItDoesntWorkOut) is great. It can even turn single elements into lists without complaints, for example.

0

u/bowbahdoe Feb 27 '23

m.get("director").get("name").asString("Alan Smithee");

If you run that code, and the name is not a String, what is the error a user will see?

1

u/rzwitserloot Feb 27 '23

None; JSON is very lightly typed, so if the input JSON is:

{"director": {"name": true}}

and you wrote the above code, I guess you want that expression to resolve to "true" (a string). If the input seems sufficiently off the rails that it is no longer feasible to try to ram the square peg in the round hole, say, you have:

{"director": {"name": {"foo": "bar"}}}

where it doesn't seem useful to say that the above expression resolves to the string "{\"foo\": \"bar\"}" or some such, I'm not quite sure, possibly "Alan Smithee", possibly in that case an exception.

JSON comes from the javascript world where you can just write:

var x = director.name;

and if you later use x in a context where strings are expected and x is true, then things mostly just kinda work. Such is the nature of languages without explicit types.

Given that JSON is from there, a library that is not based around marshalling JSON blobs into defined java classes, should cater to this model. Thus, as you read the data, you specify the type you want it to be java-side, and whatever's there, well, best effort it. Trying to be strict with JSON is a bad idea, because JSON out in the wild isn't particularly strict; most JSON APIs don't bother with an exacting definition, and things like MongoDB are built on 'all keys are optional'. If you do have a precise spec, ... why aren't you just marshalling this stuff into java classes?

Talking about 'what will the user see' makes no sense at all, we're multiple layers removed, we're not writing a library with defined user-facing output, that's ridiculous. That's akin to asking "what should ArrayList pop up in a dialog to the user if you attempt to grow it beyond 231-1 elements?". Obviously, nothing, it should have defined behaviour for that case or throw something. None of which is related in any way to 'what should the user see'.

2

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

and if you later use x in a context where strings are expected and x is true, then things mostly just kinda work. Such is the nature of languages without explicit types

One thing that appealed to me about the JsonDecoder.field(json, "name", JsonDecoder::string) approach is that custom decoders wouldn't feel like a 2nd class citizen. If someone's interpretation of how to look for a String in JSON was closer to yours there wouldn't be extra syntactic overhead to using that interpretation JsonDecoder.field(json, "name", CustomDecoders::lenientString).

With the "pathing" approach of .at("name").asString() it might be enough to say .at("name").as(CustomDecoders::lenientString), but honestly my preference at that point would be to not provide asString and only as. I recognize that wouldn't be much loved though

what will the user see' makes no sense at all, we're multiple layers removed, we're not writing a library with defined user-facing output, that's ridiculous

When I say "user" I am referring to a "user of the library" not an end user.

Specifically this is coming from people who ask "HELP, CODE NOT WORK" and share 100 lines of tree crawling + a ClassCastException. It's difficult in that context. I want those programmers to see what they were looking for and what was actually there.

1

u/rzwitserloot Feb 28 '23

Specifically this is coming from people who ask "HELP, CODE NOT WORK" and share 100 lines of tree crawling + a ClassCastException. It's difficult in that context. I want those programmers to see what they were looking for and what was actually there.

You actually made me chuckle out loud!

I spend plenty of time on StackOverflow and have given presentations for 800+ audiences before, but from context I think you're a teacher, so I can't quite match your expertise on didactics, perhaps.

However, it sure sounds like you're saying: "If only you design your library well enough, even utter fucking idiots will no longer be confused by it". That made me chuckle. You are merely a mortal. There is no fucking way you get to out-wit the inventiveness of the moron, it just doesn't work that way.

Making your API more convoluted to use and less convenient in order to cater to morons, as a consequence, is a big mistake.

1

u/bowbahdoe Feb 28 '23

but from context I think you're a teacher, so I can't quite match your expertise on didactics, perhaps.

The only experience I have is specifically being on Discord servers and doing 1 on 1 tutoring/question answering there.

The difference with the experience of stack overflow and large presentations is that there is a lot more back-and-forth, its generally 1 on 1, and people expect to be able to DM you at 1am.

I would not classify myself as an expert, but I have been at it for ~4 years and have conversations with total beginners pretty regularly.