This is overly complicated, Jackson handles lists via its writer methods just as well as it handles regular objects. This should work just fine for you, assuming I have not misunderstood your question:
public void writeListToJsonArray() throws IOException {
final List<Event> list = new ArrayList<Event>(2);
list.add(new Event("a1","a2"));
list.add(new Event("b1","b2"));
final ByteArrayOutputStream out = new ByteArrayOutputStream();
final ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(out, list);
final byte[] data = out.toByteArray();
System.out.println(new String(data));
}
Answer from Perception on Stack OverflowWhat is the best way to write a Java list to a JSON array - Stack Overflow
java - How to use Jackson to deserialise an array of objects - Stack Overflow
java - Convert List<Object[]> to JSON - Stack Overflow
java - How can I convert JSON file into List of objects? - Stack Overflow
This is overly complicated, Jackson handles lists via its writer methods just as well as it handles regular objects. This should work just fine for you, assuming I have not misunderstood your question:
public void writeListToJsonArray() throws IOException {
final List<Event> list = new ArrayList<Event>(2);
list.add(new Event("a1","a2"));
list.add(new Event("b1","b2"));
final ByteArrayOutputStream out = new ByteArrayOutputStream();
final ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(out, list);
final byte[] data = out.toByteArray();
System.out.println(new String(data));
}
I can't find toByteArray() as @atrioom said, so I use StringWriter, please try:
public void writeListToJsonArray() throws IOException {
//your list
final List<Event> list = new ArrayList<Event>(2);
list.add(new Event("a1","a2"));
list.add(new Event("b1","b2"));
final StringWriter sw =new StringWriter();
final ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(sw, list);
System.out.println(sw.toString());//use toString() to convert to JSON
sw.close();
}
Or just use ObjectMapper#writeValueAsString:
final ObjectMapper mapper = new ObjectMapper();
System.out.println(mapper.writeValueAsString(list));
First create a mapper :
import com.fasterxml.jackson.databind.ObjectMapper;// in play 2.3
ObjectMapper mapper = new ObjectMapper();
As Array:
MyClass[] myObjects = mapper.readValue(json, MyClass[].class);
As List:
List<MyClass> myObjects = mapper.readValue(jsonInput, new TypeReference<List<MyClass>>(){});
Another way to specify the List type:
List<MyClass> myObjects = mapper.readValue(jsonInput, mapper.getTypeFactory().constructCollectionType(List.class, MyClass.class));
From Eugene Tskhovrebov
List<MyClass> myObjects = Arrays.asList(mapper.readValue(json, MyClass[].class))
This solution seems to be the best for me.
Just return the list from the controller method
@RequestMapping(value = "/all", method = RequestMethod.GET)
@ResponseBody
public List<Object[]> getAllDeps() {
List<Object[]> list = departmentService.getAllDepartments();
return list;
}
The @ResponseBody annotation does the transformation for you.
public JSONObject findOccurrByFileUUID(UUID filePefin) throws JSONException {
StringBuilder strQuery = new StringBuilder();
strQuery.append("SELECT c.\"name\" AS creditorname, d.\"name\" AS debtorname, concat(b2.\"type\",'-',b2.\"number\",'-',b2.parcel) AS docto, b2.uniquenumber, to_char(b.dateoccurr,'DD/MM/YYYY HH24:MI:SS') AS dateoccur, to_char(b.createddate, 'DD/MM/YYYY HH24:MI:SS') AS createddate, b.statusnegatived, l.username FROM billnegativedoccurr b \n" +
"LEFT JOIN billnegatived b2 ON b2.uuid = b.billnegativeduuid \n" +
"LEFT JOIN creditor c ON c.tenantowner_uuid = b2.tenant_uuid AND c.uuid = b2.creditor_uuid \n" +
"LEFT JOIN debtor d ON d.tenantowner_uuid = b2.tenant_uuid AND d.uuid = b2.debtor_uuid \n" +
"INNER JOIN login l ON l.uuid = b.useroccurr \n" +
"WHERE b.filepefinuuid = :filePefin");
Query query = eM.createNativeQuery(strQuery.toString()); //no entity mapping
query.setParameter("filePefin", filePefin);
List<Object[]> queryList = query.getResultList();
JSONArray array = new JSONArray();
JSONObject obj = new JSONObject();
for (Object[] result : queryList) {
JSONObject object = new JSONObject();
object.put("creditorName", result[0]);
object.put("debtorName", result[1]);
object.put("docto", result[2]);
object.put("uniquenumber", result[3]);
object.put("dateoccur", result[4]);
object.put("createddate", result[5]);
object.put("statusnegatived", result[6]);
object.put("username", result[7]);
array.put(object);
}
return obj.put("Values", array);
}
Why are you putting your list into Map? Code looks weird. If you want to return a list, just do it:
@RequestMapping("/getGodowns")
public @ResponseBody List<CscGodownBean> getGodownsBasedOnDistrict(@RequestParam(value="district_code") String dist_code) {
List<CscGodownBean> godown_list = null;
String exception = null;
try {
//getting name and codes here
godown_list = scm_service.getGodownListBesedOnDistCode(dist_code);
} catch (Exception ex) {
ex.printStackTrace();
exception = ex.getMessage();
}
return godown_list;
}
Change the return result from Map to List<CscGodownBean> and put : retrun godown_list
So;
@RequestMapping("/getGodowns")
public @ResponseBody List<CscGodownBean>
getGodownsBasedOnDistrict(@RequestParam(value="district_code") String
dist_code) {
List<CscGodownBean> godown_list = new ArrayList<CscGodownBean>();
String exception = null;
try
{
//getting name and codes here
godown_list = scm_service.getGodownListBesedOnDistCode(dist_code);
}catch(Exception ex)
{
ex.printStackTrace();
exception = ex.getMessage();
}
return godown_list ;
}
UPDATE
And you can return result as string and you will get what you need :
@RequestMapping("/getGodowns")
public @ResponseBody String
getGodownsBasedOnDistrict(@RequestParam(value="district_code") String
dist_code) {
List<CscGodownBean> godown_list = new ArrayList<CscGodownBean>();
String exception = null;
try
{
//getting name and codes here
godown_list = scm_service.getGodownListBesedOnDistCode(dist_code);
}catch(Exception ex)
{
ex.printStackTrace();
exception = ex.getMessage();
}
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
String arrayToJson = objectMapper.writeValueAsString(godown_list);
System.out.println("Convert List to JSON :");
System.out.println(arrayToJson);
return arrayToJson ;
}
The returned String is json format.
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" }
]
}