Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java cast Arraylist to JsonElement

Tags:

java

json

ajax

gson

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;
 } 

};

like image 385
Whitney R. Avatar asked Oct 24 '25 16:10

Whitney R.


2 Answers

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

like image 58
Will C. Avatar answered Oct 26 '25 05:10

Will C.


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));
like image 38
flounder Avatar answered Oct 26 '25 07:10

flounder