How to convert arraylist to json object

public ArrayList<String> convertJsonToJsonObject(){

    ArrayList<String> mylist = new ArrayList<String> ();

 mylist.add("abc");
 mylist.add("cfd");
 mylist.add("ert");
 mylist.add("fg");
 mylist.add("ujk");
 mylist.add("wer");

 mylist.add("dvb");
 mylist.add("ert");


 System.out.println("JSONObject :: "+(JSONObject)JSONSerializer.toJson(mylist));

I got an error in the .toJson () method, I'm not sure what the error I am making is.

+4
source share
5 answers

You can use the GSON library to accomplish this.

 ArrayList<String> mylist = new ArrayList<String> ();
 mylist.add("abc");
 mylist.add("cfd");
 mylist.add("ert");
 mylist.add("fg");
 mylist.add("ujk");
 String json = new Gson().toJson(mylist);

Additional support can be found in the GSON User Guide .

+5
source
gson.toJson(object);

Gson google group

+3
source
JSONArray jsArray = new JSONArray(mylist);

or

Gson gson = new Gson();
String jsonArray = gson.toJson(mylist);

Get java-json.jar and Gson.jar here

+3
source
List<String> bibo = new ArrayList<String>();
bibo.add("obj1");
bibo.add("obj2");
bibo.add("obj3");
String json = new Gson().toJson(bibo);
+1
source
ArrayList<Domain> list = new ArrayList<Domain>();
list.add(new Domain());
list.add(new Domain());
list.add(new Domain());
String json = new Gson().toJson(list);
0
source

Source: https://habr.com/ru/post/1547462/


All Articles