DEV Community

Sorin Costea
Sorin Costea

Posted on • Originally published at tryingthings.wordpress.com

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/)

Top comments (4)

Collapse
 
alainvanhout profile image
Alain Van Hout

A similar approach, using Gson, is to use GSON.fromJson(yourstring, HashMap.class), which will converts it to a structure of maps, lists and primitives.

Collapse
 
sorincostea profile image
Sorin Costea

Not if in the string there's an array, or has nested structures, basically if you don't know what you received. My point was, with the above you can safely poke around unknown JSON structures.

Collapse
 
alainvanhout profile image
Alain Van Hout

That's also possible with map-based parsing: it parses a JSON array to a List, mostly at whichever nested depth. You of course need to do type checking, but that's equally true for the the other approach, since calling getAsInt() on a string also inherently has its costs.

Thread Thread
 
sorincostea profile image
Sorin Costea

For my lazy use case returning null (or providing a default) instead of try/catching covered 100%. Anyway vert.x solution is just a thin layer over Jackson so it's not like they reinvented the wheel... just simple things made even simpler.