logoalt Hacker News

dtechlast Thursday at 5:56 PM2 repliesview on HN

Java lacks the expressiveness to make it much better than this. There's a reason almost all the "replacement Java" languages add something to support DSLs, e.g. type safe builders in Kotlin [1]

The kotlin stdlib-adjacent json lib does it like this

   buildJsonObject {
     putJsonArray("providers") {
        add("SUN")
        add("SunRsaSign")
        add("SunEC")
     }
   }
[1] https://kotlinlang.org/docs/type-safe-builders.html

Replies

layer8last Thursday at 10:26 PM

> Java lacks the expressiveness to make it much better than this.

That's not really true. You can have a Java library providing:

    Json.writeTo(System.out)
        .object()
            .array("providers")
                .element("SUN")
                .element("SunRsaSign")
                .element("SunEC")
            .end()
        .end();
or as a shortcut

    Json.writeTo(System.out)
        .object()
            .array("providers").withElements("SUN", "SunRsaSign", "SunEC")
        .end();
or similar (aka faceted fluent API), with typed interfaces mirroring the grammar of the target language, here JSON.

This is basically a structured output iterator (or OutputStream-like) pattern. It can also support modularization such that substructures can be factored out into separate methods or lambdas, thereby also allowing loops and conditionals.

Such an API can be provided in a relatively compact fashion and would be nicer than what the JEP proposes.

pronlast Thursday at 6:06 PM

That's not the reason. The question was about JSON generation from existing Java types, not about a DSL. Java JSON libraries offer similar conveniences (in fact, you can be much more sophisticated, clear, and convenient than the DSL you've shown), but this particular library, as explicitly described in the JEP, is not intended to be a general-purpose JSON library, of which Java already has several good and popular ones.

show 1 reply