Reputation: 147
Within my entity class I have 3 Strings along with getters and setters. I am using Jackson to display results. I would like to see column and data like this...
[[id:"1", name:"Tim", address:"street"]]
However, I only get the data back without the column name as below...
[["1","Tom","street"]]
Is there a jackson annotation that would show the column name? Does this have something to do with marshalling/unmarshalling?
Entity
@Entity
@Table(name = "Personnel")
public class User implements Serializable {
private String id;
private String name;
private String address;
public User(String id, String name, String address)
{
this.id = id;
this.name = name;
this.address = address;
}
@Id
@Column(name = "name", unique = true, nullable = false)
public String getName() {
return this.name;
}....
//setters getters
Impl
@Transactional(readOnly=true)
public List<User> getUsers() throws Exception{
List<User> userList= new ArrayList<User>();
String qry = "select u.id, u.name, u.address from User as u where u.name = 'Tim'" ;
List<String> jsonrows;
Query query = sessionFactory.getCurrentSession().createQuery(qry);
userList.addAll(query.list());
return userList;
Controller
@RequestMapping(value = "/users/find", method = RequestMethod.GET, produces="application/json")
public List<User> getUserName() {
List<User> result= null;
try {
{ result = service.getUserList();
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
So I tried to use GSON and then got back numbers for my column names with the code below.
Any ideas?
Upvotes: 4
Views: 3081
Reputation: 691755
First of all, your query doesn't actually return a List<String>
. It returns a List<Object[]>
, where each array contains 3 elements: the ID, the name and the address.
Since all you have is the values contained in the column, there is no way a JSON serializer can guess that the first element of the array is an ID, the second a name and the third an address.
You would have the JSON you want if, instead of returning a List<Object[]>
, your query returned a List<User>
. Then, Gson would have objects with named fields, and could transform those Java objects to JSON objects with the same fields.
So your query should simply be
select u from User u where u.name = 'Tim'
And the method should return the List<User>
returned by this query. By the way, this method should be named getUsersNamedTim()
, and not getUser()
, which implies that the method returns only one user.
Upvotes: 3