我如何才能 Return 一个 JSON 没有来自其他 类 的嵌套对象的对象?
How can I Return a JSON Object without Nested Objects From Other Classes?
我想 return 一个 JSON 对象,其中包含来自两个不同 Class 的信息。
就像我想要来自 class 用户的用户名和来自 Class Role
的 rolename
一起在一个 JSON 对象中。
我当前的代码:
@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();
}
}
我目前得到的:
{
"role": {
"name": "ADMIN"
},
"username": "test"
}
然而,我的目标是得到这样的东西:
{
"role": "ADMIN",
"username": "test"
}
我认为您可以简单地执行以下操作。
@Projection(name = "CustomUser", types = {User.class})
public interface CustomUser {
String getUsername();
@Value("#{target.getRoles(0).getName()}")
String getRole();
}
您正在获取角色 -> 名称结构,因为 RoleTest 是一个接口,它可能有多个值。
如果您使用的是 Jackson 库,请查看@JsonUnwrapped。文档是 here
这里的问题是@JsonUnwrapped 不适用于集合。正如您在一条评论中指出的那样,如果 Role 不需要是一组,这将解决您的问题。
如果您对为什么 @JsonUnwrapped 不适用于 Collcetions 有疑问,this 将有助于进一步理解。
我想 return 一个 JSON 对象,其中包含来自两个不同 Class 的信息。
就像我想要来自 class 用户的用户名和来自 Class Role
的 rolename
一起在一个 JSON 对象中。
我当前的代码:
@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();
}
}
我目前得到的:
{
"role": {
"name": "ADMIN"
},
"username": "test"
}
然而,我的目标是得到这样的东西:
{
"role": "ADMIN",
"username": "test"
}
我认为您可以简单地执行以下操作。
@Projection(name = "CustomUser", types = {User.class})
public interface CustomUser {
String getUsername();
@Value("#{target.getRoles(0).getName()}")
String getRole();
}
您正在获取角色 -> 名称结构,因为 RoleTest 是一个接口,它可能有多个值。
如果您使用的是 Jackson 库,请查看@JsonUnwrapped。文档是 here
这里的问题是@JsonUnwrapped 不适用于集合。正如您在一条评论中指出的那样,如果 Role 不需要是一组,这将解决您的问题。 如果您对为什么 @JsonUnwrapped 不适用于 Collcetions 有疑问,this 将有助于进一步理解。