简体   繁体   中英

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 am having error at .toJson() method, I am not sure what is the mistake I am making.

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

You can refer to the GSON User Guide for more support.

JSONArray jsArray = new JSONArray(mylist);

Or

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

Get java-json.jar and Gson.jar here

gson.toJson(object);

Gson Google Group

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM