我是什么让 Json 结果像这样 ["asdf" : "adf", "asdf" : "asdf"]
但返回值类似于 [com.example.model.AccountEntity@57af674a]
@RequestMapping(value = "/getMyInfoall", produces = MediaType.APPLICATION_JSON_VALUE)
public String getMemberall(@RequestBody JSONObject sendInfo) throws IOException {
List user = UserService.findAll();
JSONObject result = new JSONObject();
result.put("data", user);
return result.toJSONString();
}
public List findAll() {
List users = UserRepository.findAll();
return users;
}
@Repository
public interface UserRepository extends JpaRepository<UserEntity, Long> {
}
@Entity(name = "Users")
@Inheritance(strategy = InheritanceType.JOINED)
public class UserEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int userkey;
@Column(nullable = false, unique = true)
private String id;
@Column(nullable = false, length = 50)
private String name;
@Column(nullable = false)
private String password;
@Column(nullable = true)
private String email;
}
@Entity(name = "Account")
public class AccountEntity extends UserEntity{
@Column(nullable = false, unique = true)
private String accountno;
@Column(nullable = true)
private String accountname;
@Column(nullable = false)
private int accountpw;
@Column(nullable = false)
private long balance;
}```
HTTPMessageConverter
s,例如Jackson 用于 JSON。
但是您也可以使用 JSON.org 的轻量级库,如 JSON-java README 中的指导:
List
转换为数组,例如
UserEntity[]
JSONArray
toString()
返回格式化为字符串的 JSON 数组 representation
List<UserEntity> userList = // a list returned from your database/repo
UserEntity[] myArr = userList.toArray(new UserEntity[userList.size()]); // (1) convert this to an array
JSONArray json = new JSONArray(myArr); // (2) follow the guide on JSON
return json.toString(); // (3) return the JSON-array as string
UserEntity
对象转换为
UserDto
DTO,然后将其返回到控制器中。依靠Jackson 而不是由您管理和创建的
JSONObject
。
public class UserDto {
private String id;
private String name;
}
您的服务应该进行映射:
public List<UserDto> findAll() {
List<UserEntity> users = UserRepository.findAll();
return users.stream().map(user -> // your mapping logic to UserDto object);
}
你的控制器只需要返回它:
@RequestMapping(value = "/getMyInfoall", produces = MediaType.APPLICATION_JSON_VALUE)
public List<UserDto> getMemberall(@RequestBody JSONObject sendInfo) throws IOException {
return UserService.findAll();
}
您可以使用 JSONObject sendInfo
执行类似的操作,并将其替换为您自己的对象。