0

I retrieve table data using SQL Query and I got:

[["Abhijith","FAZT LORRY"]] 

But I want as a JSONArray. help me please.

My service class is:

public List<Projectemployeeallocation> findAllAllocations() 
                                             throws JsonProcessingException {

    Session session = sessionFactory.openSession();

    String sql="SELECT emp.EFirstname,pro.ProjectName FROM 
                t_employeemaster emp JOIN t_projectemployeeallocation proall ON 
                emp.EmployeeAutoID=proall.EmployeeID JOIN t_projectmaster pro ON 
               proall.ProjectID=pro.ProjectID";

    Query query = session.createSQLQuery(sql);
    //query.setParameter("username", uname);
    List list = query.list();

    return list;
}
greatwolf
  • 20,287
  • 13
  • 71
  • 105
luee
  • 65
  • 2
  • 9
  • Use GSON library for that. String json = new Gson().toJson(list); – gifpif Jan 30 '17 at 10:00
  • 3
    Possible duplicate of [How to convert List to Json in Java](http://stackoverflow.com/questions/14228912/how-to-convert-list-to-json-in-java) – walen Jan 30 '17 at 10:00
  • Search how to parse a String into a Json in Java. You have a lot of API with enought tutorial to help you on internet – AxelH Jan 30 '17 at 10:09

2 Answers2

0

You could use jackson which is powerful library for JSON in java.

List<String> list = new ArrayList<>();
try {
    String result = new ObjectMapper().writerFor(new TypeReference<List<String>>(){}).writeValueAsString(list);
} catch (JsonProcessingException e) {
    e.printStackTrace();
}
Max
  • 379
  • 1
  • 8
0

As your query is returning Multiple columns, query.list() would return a List<Object[]> with each Object[] containing specified columns data for every row returned by DB.

As your query seems to return only one result you could return list.get(0) and then convert it into jsonArray using any json library such as gson,jackson etc.

Kaushik Patel
  • 239
  • 1
  • 5