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.
lospejos
1,9864 gold badges19 silver badges38 bronze badges
asked Jul 7, 2014 at 17:16
-
41. What does the error say ? 2. Which Json library are you using ?nos– nos2014年07月07日 17:21:13 +00:00Commented Jul 7, 2014 at 17:21
5 Answers 5
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.
answered Jul 7, 2014 at 17:21
Sign up to request clarification or add additional context in comments.
2 Comments
rageandqq
Be sure to include the GSON library in your project!
newbie
i am trying to convert the array into json object.JSONArray jsArray = new JSONArray(mylist); System.out.println("print the array" + jsArray); for (int i = 0; i < mylist.size(); i++) { jsArray.put(mylist.get(i)); } JSONObject obj = new JSONObject(); System.out.println("print he object" + obj);
JSONArray jsArray = new JSONArray(mylist);
Or
Gson gson = new Gson();
String jsonArray = gson.toJson(mylist);
Get java-json.jar and Gson.jar here
answered Jul 7, 2014 at 17:22
3 Comments
newbie
i got the output in array["acb ", "adg ", "tyy " ].Now i would like to convert the json array to json object.is there any way i can do it?
SparkOn
Hi whatever you are getting it is the json object
gson.toJson(object);
answered Jul 7, 2014 at 17:18
3 Comments
newbie
It says,The method toJson(ArrayList<String>) is undefined for the type Object.@Peter Liljenberg
dikkini
List<String> mylist = new ArrayList<> (); myList.add("hello"); System.out.println(new Gson().toJson(mylist));
dikkini
Oh, i understand. I give you link to Google Code of this library, you have to download it and add to dependency of your project.
ArrayList<Domain> list = new ArrayList<Domain>();
list.add(new Domain());
list.add(new Domain());
list.add(new Domain());
String json = new Gson().toJson(list);
answered Feb 28, 2017 at 11:12
2 Comments
Arun Joseph
Can U say how to retrive back the values in list?
Shaaban Ebrahim
@ArunJoshla List<Domain> videos = gson.fromJson(json, new TypeToken<List<Domain>>(){}.getType()); , json is string value that initialized last line of answer
List<String> bibo = new ArrayList<String>();
bibo.add("obj1");
bibo.add("obj2");
bibo.add("obj3");
String json = new Gson().toJson(bibo);
answered Jul 7, 2015 at 8:39
Comments
lang-java