Handling unknown JSON structures

sorincostea

Sorin Costea

Posted on July 1, 2020

Handling unknown JSON structures

JSON object mapping, marshalling, call it whatever you want, we have you covered with Gson or Jackson. Unless you don't care about structure and want to be able to parse random JSON strings. Oops, THERE come clumsiness.

I'm sure you could

    final JsonObject json = new JsonParser().parse(yourstring).getAsJsonObject();
    final Integer start = json.has("start") ? json.get("start").getAsInt() : 0;

(made possible with Google Gson) but why not go simpler and just

    final JsonObject json = new JsonObject(yourstring);
    final Integer start = json.getInteger("start", 0);

Nice, right? And the same with arrays, just json.getJsonArray("list") with or without providing defaults... Too bad it's just part of the core Vert.x package and not a separate library you could use in any project... so if you have any vertx.core dependencies lying around, for example when using Quarkus Lambda HTTP, or don't mind an extra 1M in size, make sure you give it a try. Cleaner simply doesn't exist in the Java world, at least as far as I know.

Ah yes, and it’s a I-JSON implementation (RFC 7493, Internet JSON) so maybe some fancy number formats won’t be able to fit, but I never hit that wall.

(Published as part of the #100DaysToOffload challenge https://100daystooffload.com/)

💖 💪 🙅 🚩
sorincostea
Sorin Costea

Posted on July 1, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related