[英]Spring ResponseEntity not returning all object attributes
I am using JPA to return an object from a database using a rest controller. 我正在使用JPA使用rest控制器从数据库返回对象。 My problem is that when I use the repo.findOne()
method to return a single object, and I return that single object, the JSON returned to the client is missing most of the objects attributes. 我的问题是,当我使用repo.findOne()
方法返回单个对象,并且返回单个对象时,返回给客户端的JSON缺少大多数对象属性。 ie return new ResponseEntity<>(objectA, HttpStatus.OK);
即返回new ResponseEntity<>(objectA, HttpStatus.OK);
However if I place objectA into an array, and return the array ie return new ResponseEntity<>(arrayWithObjectA, HttpStatus.OK);
但是,如果我将objectA放入数组中,然后返回该数组,即return new ResponseEntity<>(arrayWithObjectA, HttpStatus.OK);
the correct JSON is returned to the client with all attributes. 带有所有属性的正确JSON返回给客户端。 Can anyone explain why this is so? 谁能解释为什么会这样?
Thanks 谢谢
Create a ResponseHandler.java file and write below code 创建一个ResponseHandler.java文件并编写以下代码
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
public class ResponseHandler {
public static ResponseEntity<Object> generateResponse(HttpStatus status, boolean error,String message, Object responseObj) {
Map<String, Object> map = new HashMap<String, Object>();
try {
map.put("timestamp", new Date());
map.put("status", status.value());
map.put("error", error);
map.put("message", message);
map.put("data", responseObj);
return new ResponseEntity<Object>(map,status);
} catch (Exception e) {
map.clear();
map.put("timestamp", new Date());
map.put("status", HttpStatus.INTERNAL_SERVER_ERROR.value());
map.put("message", e.getMessage());
return new ResponseEntity<Object>(map,status);
}
}
Now in your api use 现在在您的api中使用
return ResponseHandler.generateResponse(HttpStatus.OK,false,"Write some message", objectA);
Return type of your method should be ResponseEntity<Object>
方法的返回类型应为ResponseEntity<Object>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.