Skip to content
May 4, 2011 / marrowboy

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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: