I am generating Rest Services using Jackson. I am able to get JSON response like
[{"userName":"scott","userId":7},{"userName":"toe","userId":101}]
but i am expecting response with Pojo name pointing to the response like below
{"UserDetails":[{"userName":"scott","userId":7},{"userName":"toe","userId":101}]}
Here is my implementation class
@Service("userServices")
public class UserServiceImpl implements UserServices{
private UserServices userServices;
public UserServices getUserServices() {
return userServices;
}
public void setUserServices(UserServices userServices) {
this.userServices = userServices;
}
@Override
public List<UserDetails> getUser(UserDetails userDetails) {
ObjectMapper mapper = new ObjectMapper();
List<UserDetails> user = new ArrayList<UserDetails>();
List<UserDetails> list = new ArrayList<UserDetails>();
UserDetails userDetails2 = new UserDetails();
userDetails2.setUserName("scott");
userDetails2.setUserId(007);
UserDetails userDetails3 = new UserDetails();
userDetails3.setUserName("toe");
userDetails3.setUserId(101);
user.add(userDetails2);
user.add(userDetails3);
try{
String jsonString = mapper.writeValueAsString(user);
UserDetails[] userDetails4 = mapper.readValue(jsonString, UserDetails[].class);
list = Arrays.asList(userDetails4);
System.out.println(userDetails4);
}catch (Exception e) {
System.out.println(e);
}
return list;
}
}
and here is my pojo
public class UserDetails implements Serializable{
private String userName;
private int userId;
public UserDetails(){
}
//getters and setters...
}
** Note:** I don't want to use any annotations at the domain object side.
You can use objectMapper.writeValueAsString(aCustomMap)
for custom json view creation on the fly.
Example:
UserDetails userDetails2 = new UserDetails();
userDetails2.setUserName("scott");
userDetails2.setUserId(007);
UserDetails userDetails3 = new UserDetails();
userDetails3.setUserName("toe");
userDetails3.setUserId(101);
Map<String, List<UserDetails>> m = new HashMap<>();
m.put("UserDetails", Arrays.asList(userDetails2, userDetails3));
System.out.print(
//This is what you need
objectMapper.writeValueAsString(m)
);
//{"UserDetails":[{"userName":"scott","userId":7},{"userName":"toe","userId":101}]}