Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

FR: Convenience methods for get in JsonObject and JsonArray #2430

Open
sam-hieken opened this issue Jul 6, 2023 · 1 comment
Open

FR: Convenience methods for get in JsonObject and JsonArray #2430

sam-hieken opened this issue Jul 6, 2023 · 1 comment

Comments

@sam-hieken
Copy link

Problem solved by the feature

Makes traversing generic JsonObject and JsonArray objects faster and easier.

Feature description

I'd like to add convenience methods to JsonArray and JsonObject, so that each has methods based on their respective get to directly get each type (int, double, boolean, etc.), rather than having to go through a JsonElement first.

For example, consider the following scenario: I want to retrieve the "name" property of the third employee.

currently, with a generic JsonObject, it would look something like this:

JsonObject obj;
String name = obj.get("employees").getAsJsonArray()
     .get(2).getAsJsonObject()
     .get("name").getAsString();

versus with my fork, which would allow the following as an alternative:

JsonObject obj;
String name = obj.getJsonArray("employees")
	.getJsonObject(2)
	.getString("name");

Alternatives / workarounds

The alternative is described above in my example.

One final note, I'm more than willing to (and have began to) implement these convenience methods myself; I just want to make sure this is a welcome change before I create and document all of them in a new fork.

Thank you!

@eamonnmcmanus
Copy link
Member

This is similar to #1291. I'm inclined to agree with @lyubomyr-shaydariv there:

It would cause API bloating: this would require the entire get***(name) and is***(name) method family to be replicated in JsonObject and get***(index) and is***(index) to be replicated in JsonArray respectively. Having .get(name)/.get(index) is simpler to design and guarantees that you can always access whole JsonElement API not worrying that some APIs are not replicated to JsonObject or JsonArray.

The JsonElement hierarchy is probably the clunkiest part of the Gson API, but if we double the size of JsonObject with new methods then it will still be clunky but even more confusing than it is today.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants