简体   繁体   中英

How get json array value format?

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;
}

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();
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM