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
Answer from code_fish on Stack Overflowresponse.getWriter().write(json);
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.
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" }
]
}
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.
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", "abc@yahoo.com")));
jsons.add(new JSONObject(ImmutableMap.of("Attribute1", "EmailAddress3", "Value1", "abc@yahoo.com1")));
System.out.println(new ObjectMapper().writeValueAsString(jsons));
The output is
[{"Value":"abc@yahoo.com","Attribute":"EmailAddress"},{"Attribute1":"EmailAddress3","Value1":"abc@yahoo.com1"}]
I suspect there are some toString() method in any object that you have override?
If you need to convert to String use the com.fasterxml.jackson.databind.ObjectMapper
Ex:
List<Integer> myList = new ArrayList<>();
myList.add(1);
myList.add(2);
ObjectMapper mapper = new ObjectMapper();
try {
String json = mapper.writeValueAsString(myList);
System.out.println("result = " + json);
//System.out.println(json);
} catch (JsonProcessingException e) {
//
}
If you want just to convert the list to json, you can use Gson:
List<Integer> myList = new ArrayList<>();
myList.add(1);
myList.add(2);
String json = new Gson().toJson(myList);
If you want that the key will be "List", you need to create a object with a member that call List and then convert it.
Iterate through the list in reverse and upon each iteration create a new JsonNode for the list element, add the previous JsonNode as a child to the new JsonNode and overwrite the original reference with the new JsonNode. Rinse and repeat.
Something like...
final String value = "BMW"; // whatever the final "value" is.
final ObjectMapper objectMapper = new ObjectMapper();
ObjectNode json = null;
for (int i = list.size() - 1; i >= 0; i--) {
final String prop = list.get(i);
final ObjectNode objectNode = objectMapper.createObjectNode();
if (json == null) {
objectNode.put(prop, value);
} else {
objectNode.put(prop, json);
}
json = objectNode;
}
Here is the piece of code which you need
package uk.co.vishal;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Answer {
public static void main(String[] args) throws JsonProcessingException {
List<String> data = new ArrayList<>();
data.add("user");
data.add("car");
data.add("brand");
System.out.println(data.toString());
Map<String, String> mydata = new HashMap<>();
Map<String, JSONObject> newdata = new HashMap<>();
JSONObject result = new JSONObject();
boolean flag = true;
for (int i = data.size() - 1; i >= 0; i--) {
if (flag) {
mydata.put(data.get(i), "BMW");
result = generateJson(mydata);
flag = false;
} else {
newdata.put(data.get(i), result);
result = generateJson(newdata);
newdata.clear();
}
}
System.out.println(result);
/*
* Here is the output:
* {
"user": {
"car": {
"brand": "BMW"
}
}
}
*
* */
}
private static JSONObject generateJson(Map data) {
return new JSONObject(data);
}
}
I hope you will be sorted !!