How to add ArrayList<String> to JSON Array - keeping type safety in mind

Brenne picture Brenne · Aug 20, 2013 · Viewed 26.8k times · Source

Eclipse displayed a type safety warning and I tried nearly everything to eradicate it (of course suppressing it would be an option) but unfortunately I hadn't any success.
Do you know how I have to change my code so that there is no type safety warning anymore. Or is @SuppressWarnings("unchecked") the only way?

ArrayList<String> arrayList= (ArrayList<String>) Classname.getArrayList();      
JSONArray obj = new JSONArray();
obj.addAll(arrayList); 

in the last line following type safety warning is displayed:

Type safety: The method addAll(Collection) belongs to the raw type ArrayList. References to generic type ArrayList should be parametrized

JSONArray is fromorg.json.simple.JSONArray. Would you recommend another package?

Answer

Felquir picture Felquir · Aug 20, 2013

If you want to work with json go this library, this library has a nice support https://code.google.com/p/google-gson/.

This is an example:

Gson gson = new Gson();
Collection<Integer> ints = Lists.immutableList(1,2,3,4,5);

(Serialization)
String json = gson.toJson(ints); ==> json is [1,2,3,4,5]

Thanks