ralfstx / minimal-json

A fast and small JSON parser and writer for Java
MIT License
732 stars 186 forks source link

UnsupportedOperationException: Not a string: null #103

Open CLOVIS-AI opened 6 years ago

CLOVIS-AI commented 6 years ago

Here's a small example of the problem:

JsonObject json = new JsonObject();
json.add("test", (String) null);
String content = json.getString("test", "default");

When running this, an UnsupportedOperationException is thrown. According to the doc of getString, however:

If this object does not contain a member with this name, the given default value is returned.

So I would expect that it would return the default value (since the value null is used to notify that there is no value).

The only way currently to bypass the exception is to set the code to:

String content = json.get("test").isNull() ? "default" : json.getString("test", "default");

which is a lot for not much (and it's badly-optimized because there are two get calls).

It would be nice if the methods would just return the default value if the content is null...

CLOVIS-AI commented 6 years ago

Here is an example of a use-case, from reading the contents of a REST response:

JsonObject values = new Request(GET, "/users/" + ID + "/")
  .get()
  .asObject();

// Use the old value as default value: if nothing is specified, keep the old value
name =      values.getString("name", name);
avatar =    values.getString("avatar", avatar);
bio =       values.getString("bio", bio);
isBanned =  values.getBoolean("banned", isBanned);

This throws an exception because the server always sends empty fields when there is no value (eg. no bio -> there is a 'bio' field but its value is 'null').

Since "no value" and "value is null" is essentially the same (especially for Strings, in which you can specify "" to say 'empty'), it would be nice that this simple code would work instead of throwing exceptions.

CLOVIS-AI commented 6 years ago

And in the case where you actually want to know if the object contains the literal null, you could still use json.get("test").isNull() so no feature is lost.

CLOVIS-AI commented 5 years ago

This would make working with this API a lot easier, please at least consider it.