I have following Rest service which queries a database, constructs multiple "Chat"-objects and returns them as an array:
@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);
}
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;
[{"userId1":"414","userId2":"12"}]
You need to have both getter and setter in your POJO for the inner map.
public class Chat {
private HashMap<String, String> msgs;
public void setMsgs(HashMap<String, String> msgs) {
this.msgs = msgs;
}
// rest of the code ...
}
If you don't want to change pojo implementation for some reason, you can setup Jackson to use private fields and not getters/setters, something like this: how to specify jackson to only use fields - preferably globally
For some reason your serverside sends you
"maps":{"entry":[{"key":"key1","value":"value1"}]}
instead of
"maps":{"key1":"value1","key2":"value2"}
You can probably solve it with just client side pojo changes like this:
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"));
}