I want to return a JSON Object with information from two different Classes.
Like I want the username from the class User and the rolename
from the Class Role
together in one JSON Object.
My current code:
@Entity
@DynamicUpdate
public class User {
private String username;
private String phone;
private String email;
private Set<Role> role;
}
@Entity
public class Role {
private int idRole;
private String name;
}
@Projection(name = "CustomUser", types = {User.class})
public interface CustomUser {
String getUsername();
RoleTest getRole();
interface RoleTest {
String getName();
}
}
@Repository
public interface UserRepository extends JpaRepository<User, Integer> {
List<CustomUser> findAllBy();
}
@Controller
@RequestMapping
public class UserController {
@Autowired
private UserRepository userRepository;
@GetMapping
@ResponseStatus(HttpStatus.ACCEPTED)
public @ResponseBody List<CustomUser> getAllUsers() {
return userRepository.findAllBy();
}
}
What I currently get:
{
"role": {
"name": "ADMIN"
},
"username": "test"
}
However, my goal is it to get something like this:
{
"role": "ADMIN",
"username": "test"
}
If you are using the Jackson library, please check @JsonUnwrapped. The documentation is here
The problem here is that @JsonUnwrapped doesn't work with the Collections. As you indicated in one of your comments if the Role need not be a set, this will solve your problem. If you have questions on why the @JsonUnwrapped doesn't work with the Collcetions, this will help to understand further.