I would like use this method:
json.add("myText", getList(id));
The function getList(id) return an arraylist, but the method json.add would like a JsonElement.
So, how can i cast an arraylist in JsonElement ?
I test this, but it doesn't work:
json.add("myText", (JsonElement)getList(id));
I test this too:
JsonElement jelement = new JsonElement() {
private ArrayList<String> list= new ArrayList<String>(); public ArrayList<String> getList(){ return this.list; }};
com.google.gson has methods for serializing an ArrayList (or any collection). Once you have serialized it, you can parse the string with a JSONParser:
JSONParser.parse(gson.toJson(getList(id)));
ref: https://sites.google.com/site/gson/gson-user-guide#TOC-Array-Examples
In order to get a JsonElement out of a List, you can use JsonTree:
List<String> myList = new ArrayList<>();
jsonObject.add("myList", gson.toJsonTree(myList));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With