JSON in statically-typed languages
JSON libraries in Java sadden me – there is an impedence mismatch between JSON and static typing.
If we have:
{ "key" : "Jackie" }
then we’d want jsonObject.get("key") to return a String. If we have
{ "key" : 66 }
then we’d want an int. It’s easy to imagine situations where we could want another jsonObject, or an array, or a boolean etc.
So what is the return type of jsonObject.get(String)? We don’t know what it will be, until runtime. This is irreconcilable with a static type system where types needs to be known at compile time, so JSON in Java is doomed to be a bit awkward. The common approaches seem to be:
- return a supertype like JsonElement which we then have to test to see what kind of thing it is, or
- have lots of .getAsInt(String), .getAsArray(String) kind of methods.
Neither of which is very nice. Hence – jsonschema (and jsonschema2pojo), JSONx (*shudder*) et al.
Just for reference, here’s how it looks in my favourite dynamic language:
(jsonObject :key)
Leave a comment