[英]How can I Return a JSON Object without Nested Objects From Other Classes?
I want to return a JSON Object with information from two different Classes. 我想返回一个JSON对象,其中包含来自两个不同类的信息。 Like I want the username from the class User and the
rolename
from the Class Role
together in one JSON Object. 就像我想要来自User类的用户名和来自Class
Role
的rolename
一起放在一个JSON对象中。
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"
}
I think you could simply do the following. 我想你可以简单地做以下事情。
@Projection(name = "CustomUser", types = {User.class})
public interface CustomUser {
String getUsername();
@Value("#{target.getRoles(0).getName()}")
String getRole();
}
You're getting the role -> name structure because RoleTest is an interface and it might have multiple values. 您将获得角色 - >名称结构,因为RoleTest是一个接口,它可能有多个值。
If you are using the Jackson library, please check @JsonUnwrapped. 如果您使用的是杰克逊图书馆,请查看@JsonUnwrapped。 The documentation is here
文档在这里
The problem here is that @JsonUnwrapped doesn't work with the Collections. 这里的问题是@JsonUnwrapped不适用于集合。 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.
如果您对@JsonUnwrapped不能与Collcetions一起使用有疑问, 这将有助于进一步理解。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.