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.
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.
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.
JSONObject obj = new JSONObject(); List<String> sList = new ArrayList<String>(); sList. add("val1"); sList. add("val2"); obj. put("list", sList);
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.
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
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