Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 530
newbie Avatar asked Jul 07 '14 17:07

newbie


People also ask

Can we convert list to JSON in Java?

We can convert a list to the JSON array using the JSONArray. toJSONString() method and it is a static method of JSONArray, it will convert a list to JSON text and the result is a JSON array.

Can we convert list to object in Java?

Core Java bootcamp program with Hands on practiceA list can be converted to a set object using Set constructor. The resultant set will eliminate any duplicate entry present in the list and will contains only the unique values. Set<String> set = new HashSet<>(list); Or we can use set.

How do I add a list to a JSON object in Java?

JSONObject obj = new JSONObject(); List<String> sList = new ArrayList<String>(); sList. add("val1"); sList. add("val2"); obj. put("list", sList);

Can we convert ArrayList to String?

To convert the contents of an ArrayList to a String, create a StringBuffer object append the contents of the ArrayList to it, finally convert the StringBuffer object to String using the toString() method.


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

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

like image 163
rageandqq Avatar answered Oct 04 '22 12:10

rageandqq


JSONArray jsArray = new JSONArray(mylist);

Or

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

Get java-json.jar and Gson.jar here

like image 40
SparkOn Avatar answered Oct 04 '22 10:10

SparkOn