You should convert your list to a JSON Array, and just use its toString() function:
JSONArray myArray = new JSONArray(jsonObjlist);
// ...
String arrayToJson = myArray.toString(2);
The int parameter specifies the indent factor to use for formatting.
Answer from Florian Albrecht on Stack OverflowYou should convert your list to a JSON Array, and just use its toString() function:
JSONArray myArray = new JSONArray(jsonObjlist);
// ...
String arrayToJson = myArray.toString(2);
The int parameter specifies the indent factor to use for formatting.
You can also direct use
String jsonString = new ObjectMapper().writeValueAsString(jsonObjectList)
To get the desired ouptput
Here is the small example
List<JSONObject> jsons = new ArrayList<>();
jsons.add(new JSONObject(ImmutableMap.of("Attribute", "EmailAddress", "Value", "[email protected]")));
jsons.add(new JSONObject(ImmutableMap.of("Attribute1", "EmailAddress3", "Value1", "[email protected]")));
System.out.println(new ObjectMapper().writeValueAsString(jsons));
The output is
[{"Value":"[email protected]","Attribute":"EmailAddress"},{"Attribute1":"EmailAddress3","Value1":"[email protected]"}]
I suspect there are some toString() method in any object that you have override?
Videos
Use GSON library for that. Here is the sample code
List<String> foo = new ArrayList<String>();
foo.add("A");
foo.add("B");
foo.add("C");
String json = new Gson().toJson(foo );
Here is the maven dependency for Gson
<dependencies>
<!-- Gson: Java to Json conversion -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.2.2</version>
<scope>compile</scope>
</dependency>
</dependencies>
Or you can directly download jar from here and put it in your class path
http://code.google.com/p/google-gson/downloads/detail?name=gson-1.0.jar&can=4&q=
To send Json to client you can use spring or in simple servlet add this code
response.getWriter().write(json);
You need an external library for this.
JSONArray jsonA = JSONArray.fromObject(mybeanList);
System.out.println(jsonA);
Google GSON is one of such libraries
You can also take a look here for examples on converting Java object collection to JSON string.
Take a look at this tutorial. Also you can parse above json like :
JSONArray arr = new JSONArray(yourJSONresponse);
List<String> list = new ArrayList<String>();
for(int i = 0; i < arr.length(); i++){
list.add(arr.getJSONObject(i).getString("name"));
}
Simplest and correct code is:
public static String[] toStringArray(JSONArray array) {
if(array==null)
return new String[0];
String[] arr=new String[array.length()];
for(int i=0; i<arr.length; i++) {
arr[i]=array.optString(i);
}
return arr;
}
Using List<String> is not a good idea, as you know the length of the array.
Observe that it uses arr.length in for condition to avoid calling a method, i.e. array.length(), on each loop.
Using gson it is much simpler. Use following code snippet:
// create a new Gson instance
Gson gson = new Gson();
// convert your list to json
String jsonCartList = gson.toJson(cartList);
// print your generated json
System.out.println("jsonCartList: " + jsonCartList);
Converting back from JSON string to your Java object
// Converts JSON string into a List of Product object
Type type = new TypeToken<List<Product>>(){}.getType();
List<Product> prodList = gson.fromJson(jsonCartList, type);
// print your List<Product>
System.out.println("prodList: " + prodList);
public static List<Product> getCartList() {
JSONObject responseDetailsJson = new JSONObject();
JSONArray jsonArray = new JSONArray();
List<Product> cartList = new Vector<Product>(cartMap.keySet().size());
for(Product p : cartMap.keySet()) {
cartList.add(p);
JSONObject formDetailsJson = new JSONObject();
formDetailsJson.put("id", "1");
formDetailsJson.put("name", "name1");
jsonArray.add(formDetailsJson);
}
responseDetailsJson.put("forms", jsonArray);//Here you can see the data in json format
return cartList;
}
you can get the data in the following form
{
"forms": [
{ "id": "1", "name": "name1" },
{ "id": "2", "name": "name2" }
]
}
For anyone else who might need this:
String jsonString = "[\"string1\",\"string2\",\"string3\"]";
ObjectMapper mapper = new ObjectMapper();
List<String> strings = mapper.readValue(jsonString, List.class);
As ryzhman said, you are able to cast it to a List, but only of the object (JSONArray in ryzhman's case) extends the ArrayList class. You don't need an entire method for this. You can simply:
List<String> listOfStrings = new JSONArray(data);
Or if you are using IBM's JSONArray (com.ibm.json.java.JSONArray):
List<String> listOfStrings = (JSONArray) jsonObject.get("key");
You can use the Gson Library.
List<String> list;
String json = new Gson().toJson(list);
Edited:
Just to have the complete answer here: The problem is that you are converting the json String into a List<String>. This way you are losing the relation key-value. The correct should be convert the json string into a HashMap<>.
It seems like your real problem is that when you originally turned the JSON string into a List, you threw away the keys. And that is not surprising, a List is not a natural representation of a JSON object (i.e. a thing with key - value pairs). You probably should have represented it as a Map.
But anyway, if you threw away the keys you've go a problem. You need to either you change your data structure to not throw the keys away, or reconstruct the JSON by inferring what the keys should be based on (for instance) their position in the list. (The latter could be a bit dodgy because the order of the name/value pairs in the original JSON should not signify anything ... and could be "random" or "implementation dependent".
JSONArray att = new JSONArray(YourList);
You can use Gson to convert List<String> to JSON
List<String> listStrings = new ArrayList<String>();
listStrings.add("a");
listStrings.add("b");
Gson objGson = new Gson();
System.out.println(objGson.toJson(listStrings));
Output
["a","b"]