Skip to content

Make JSONArray and JSONObject generic and add a getAsObject() and getAsArray() methods to JSONObject class #215

New issue

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

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

Already on GitHub? # to your account

Open
SuperPat45 opened this issue Sep 26, 2024 · 2 comments

Comments

@SuperPat45
Copy link

SuperPat45 commented Sep 26, 2024

Can you make JSONArray generic:, so we can write:
JSONArray<JSONObject> array = new JSONArray<JSONObject>();

JSONObject can also be generic for the value:
JSONObject<String> object = new JSONObject<String>();

To remove the need of castings when getting an object or an array, add, in the JSONObject class, two methods getAsObject() and getAsArray() methods:

function <T> JSONObject<T> getAsObject(String key) {
}
function <T> JSONArray<T> getAsArray(String key) {
}

If the map or the collection is not a JSONObject or JSONArray, the method will convert it.

This can be used easily without cast and throw an Exception if the value is not a map:
JSONObject<String> object = jsonObjectParent.getAsObject("childObject");

Like for an array::

JSONArray<String> array = jsonObjectParent.getAsArray("childObject");
for (String item : array) {
}
@UrielCh
Copy link
Contributor

UrielCh commented Oct 8, 2024

Adding generic in JSONObject and JSONArray, will break old codes, in Java, generics cannot have default types.

I lost hope that one day this code will be valid in JAVA:

public class JSONArray<E = Object> extends ArrayList<E> implements List<E>, JSONAwareEx, JSONStreamAwareEx {
}

Or I need to add some new generics JSONTypedArray<E> and JSONTypedObject<E> and implements class JSONArray by class JSONArray extends JSONTypedArray<Object>

@SuperPat45
Copy link
Author

SuperPat45 commented Oct 8, 2024

Adding generic in JSONObject and JSONArray, will break old codes

Maybe for a JSON-Smart v3

wubenxin added a commit to wubenxin/json-smart-v2 that referenced this issue Apr 12, 2025
pcHwang2 pushed a commit to pcHwang2/json-smart-v2 that referenced this issue Apr 12, 2025
pcHwang2 added a commit to pcHwang2/json-smart-v2 that referenced this issue Apr 12, 2025
# for free to join this conversation on GitHub. Already have an account? # to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants