Open mpost opened 9 years ago
If I understand correctly, your suggestion is to add methods like getInt(String)
, getBoolean(String)
, etc. to JsonObject
. These methods would return a "default fallback value" if the object does not contain a member with the given name. The obvious default value would be the initial value of the respective type (0
for int, false
for boolean, etc.).
Those methods would be ambiguous, as in case of returning the "default fallback value" you could not tell whether the member is present or not. For example, jsonObject.getInt("size")
returning 0
could mean that the size was specified as 0
, but also that the "size" attribute is missing in the JSON object.
Of course, the same is true for jsonObject.getInt("size", 0)
, but here it's explicit in the code that if the size is not present it is assumed to be 0. From my point of view, the savings are little compared to the risk of programming errors that would be introduced by the suggested API.
I follow your reasoning to limit the scope of this library. My use case is to serialize a json object to a regular java object where leaving values in their default state would be the expected deserialization outcome. Therefore i have a lot of redundant method parameters that pass in the default java value. If you think the feature is out of scope, feel free to close the issue.
@ralfstx Is there a reason JsonObject
has not explicit has(String name)
method to check if the member is present or not?
To check this now I have to do jsonObject.get("the_name") != null
, while something like jsonObject.has("the_name)
would be preferable.
@marceloverdijk I was surprised to find that there wasn't a has
or contains
. Seems to be in every other json library. You can also use names().contains(...)
.
Having to supply a default value on the JsonObject.getXXX methods is sometimes a bit tedious. Often times you just want the string to be null or the boolean to be false. So there should be a variant where it is not required to provide a default value.