简体   繁体   English

spring api - jackson将一个对象序列化为一个数组

[英]spring api - jackson serialize an object to an array

I'm encountering a problem about the way jackson serialize an object. 我遇到了关于杰克逊序列化对象的方式的问题。

I have a class 我上课了

public List<Solution> getSolutionForSearching() {
   String hql = "SELECT id,description  FROM Solution";         
     Session session = solutionDao.getSession();        
     Query query =session.createQuery(hql);         
     return query.list();   
}

I only wanted to select id and description from database: 我只想从数据库中选择id和description:

 [ { id: 35, description: "12" }, { id: 36, description: "1a"   }]

And I expected the response is an array of objects 我希望响应是一个对象数组

[ [35, "12" ], [  36, "1a"  ]]

but the obtained result is an array of arrays 但获得的结果是一个数组数组

 [ [35, "12" ], [ 36, "1a" ]] 

How to serialize the response data to match the requirements? 如何序列化响应数据以符合要求?

You hql query does not return instances of type Solution . 您的hql查询不返回Solution类型的实例。 Instead it returns int, String pairs. 相反,它返回int,String对。 So the Jackson cannot map them to the correct form. 所以杰克逊无法将它们映射到正确的形式。

You should either return complete objects Solution from the database, or you map the results of the query to Solution object before you pass it to Jackson. 您应该从数据库返回完整对象Solution ,或者在将查询结果传递给Jackson之前将查询结果映射到Solution对象。

Currently your Solution object is very small, so you don't have to worry about the performance. 目前,您的Solution对象非常小,因此您不必担心性能问题。 Just modify the hql query like this: 只需像这样修改hql查询:

String hql = "SELECT solution FROM Solution solution"; 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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