我有以下Rest服务查询数据库,构建多个" Chat" -objects并将它们作为数组返回:
@GET
@Path("/getChats")
@Produces(MediaType.APPLICATION_JSON)
public Chat[] getChats(@QueryParam("userId") String userId){
ArrayList<Chat> chats = getChatsDB(userId);
Chat[] chatAr = new Chat[chats.size()];
return chats.toArray(chatAr);
}
&#34; Chat&#34; -class是POJO:
import java.util.HashMap;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@JsonIgnoreProperties(ignoreUnknown = true)
public class Chat {
private String userId1;
private String userId2;
private HashMap<String, String> msgs;
public Chat() {
msgs = new HashMap<>();
}
public String getUserId1() {
return userId1;
}
public void setUserId1(String userId1) {
this.userId1 = userId1;
}
public String getUserId2() {
return userId2;
}
public void setUserId2(String userId2) {
this.userId2 = userId2;
}
public void addMsg(String date, String msg){
msgs.put(date, msg);
}
public HashMap<String, String> getMsgs() {
return msgs;
}
}
获取此聊天对象的客户端代码是:
public static Chat[] getChats() {
Chat[] chats = null;
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
String chatUrl = url+"getChats?userId="+user.getId();
chats = restTemplate.getForObject(chatUrl, Chat[].class);
for(Chat c: chats){
System.out.println(c.getUserId1());
System.out.println(c.getUserId2());
for(Map.Entry<String,String> e : c.getMsgs().entrySet()){
System.out.println(e.getKey() + e.getValue());
}
}
return chats;
客户端收到聊天对象,但没有带有消息的HashMap。 c.getUserId1和c.getUserId2返回正确的值,但HashMap为空。此问题仅在客户端。 servicemethod getChats(@QueryParam(&#34; userId&#34;)String userdd)中的chat-objects在HashMap中具有正确的值。
在浏览器中打开链接显示:
[{&#34; userId1&#34;:&#34; 414&#34;&#34; userId2&#34;:&#34; 12&#34;}]
答案 0 :(得分:1)
您需要在POJO中同时使用getter和 setter 作为内部地图。
public class Chat {
private HashMap<String, String> msgs;
public void setMsgs(HashMap<String, String> msgs) {
this.msgs = msgs;
}
// rest of the code ...
}
如果您由于某种原因不想更改pojo实现,可以设置Jackson使用私有字段而不是getter / setter,如下所示:how to specify jackson to only use fields - preferably globally
出于某种原因,您的服务器端会向您发送
"maps":{"entry":[{"key":"key1","value":"value1"}]}
instead of
"maps":{"key1":"value1","key2":"value2"}
你可以用这样的客户端pojo改变解决它:
public void setMsgs(Map<String, List<Map<String,String>>> entries){
for (Map<String, String> entry: entries.get("entry"))
msgs.put(entry.get("key"),entry.get("value"));
}