Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java Spring返回一个带有@ResponseBy的修改过的JSONObject_Java_Json_Spring_Rest - Fatal编程技术网

Java Spring返回一个带有@ResponseBy的修改过的JSONObject

Java Spring返回一个带有@ResponseBy的修改过的JSONObject,java,json,spring,rest,Java,Json,Spring,Rest,我正在使用SpringMVC,并试图从我的控制器返回一个JSONObject。我已经用@ResponseBody注释了该方法,以便它将控制器返回的JSONObject放入ResponseBody。 这是我的控制器: @GetMapping(value="/student/{roll}",produces="application/json") @ResponseBody private JSONObject getStudentDetails(@PathVariable(value="roll"

我正在使用SpringMVC,并试图从我的控制器返回一个JSONObject。我已经用@ResponseBody注释了该方法,以便它将控制器返回的JSONObject放入ResponseBody。 这是我的控制器:

@GetMapping(value="/student/{roll}",produces="application/json")
@ResponseBody
private JSONObject getStudentDetails(@PathVariable(value="roll") String roll) {
    JSONObject response = new JSONObject();
    Student student = studentDAO.getStudent(roll);
    response.put("firstName",student.getFirstName());
    response.put("lastName",student.getLastName());
    response.put("roll",student.getRoll());
    response.put("email",student.getEmail());
    response.put("course",student.getCourse());
    response.put("stream",student.getStream());
    response.put("year",student.getYear());
    response.put("gender",student.getGender());
    String date = null;
    DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    try {
        date = String.valueOf(df.parse(student.getSignUpDate()).getTime());
    } catch (ParseException e) {
        e.printStackTrace();
    }
    response.put("signUpDate", date);
    System.out.println("Response Body::::: "+response.toString());
    return response;
}
有效的响应应如下所示:

{
  "firstName": "John",
  "lastName": "Doe",
  "gender": "M",
  "stream": "cse",
  "year": 3,
  "roll": "2013BT2011",
  "course": "btech",
  "signUpDate": "1476224877000",
  "email": "john@doe.com"
}
但我明白了:

{
  "map": {
    "firstName": "John",
    "lastName": "Doe",
    "gender": "M",
    "stream": "cse",
    "year": 3,
    "roll": "2013BT2011",
    "course": "btech",
    "signUpDate": "1476224877000",
    "email": "john@doe.com"
  }
}
这里,我的控制器返回的对象被包装成一个映射对象,然后由Spring返回

谁能告诉我这里怎么了。
任何帮助都将不胜感激。:)

SpringMVC使用jackson数据绑定将对象序列化为JSON/将JSON反序列化为对象。 因此,不需要返回带有@ResponseBody的JSONObject。 有一些方法:

用需求字段定义一个类(视图对象),然后新建、填充一个实例并返回它

使用java.util.Map。因此,您的代码如下所示:

@GetMapping(value="/student/{roll}",produces="application/json")
@ResponseBody
private Map<String, Object> getStudentDetails(@PathVariable(value="roll") String roll) {
      Map<String, Object> response = new HashMap<>();
  Student student = studentDAO.getStudent(roll);
  response.put("firstName",student.getFirstName());
  response.put("lastName",student.getLastName());
  response.put("roll",student.getRoll());
  response.put("email",student.getEmail());
  response.put("course",student.getCourse());
  response.put("stream",student.getStream());
  response.put("year",student.getYear());
  response.put("gender",student.getGender());
  String date = null;
  DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  try {
    date = String.valueOf(df.parse(student.getSignUpDate()).getTime());
  } catch (ParseException e) {
    e.printStackTrace();
  }
  response.put("signUpDate", date);
  System.out.println("Response Body::::: "+response.toString());
  return response;
}
@GetMapping(value=“/student/{roll}”,products=“application/json”)
@应答器
私有映射getStudentDetails(@PathVariable(value=“roll”)字符串roll){
Map response=newhashmap();
Student=studentDAO.getStudent(roll);
response.put(“firstName”,student.getFirstName());
response.put(“lastName”,student.getLastName());
response.put(“roll”,student.getRoll());
response.put(“email”,student.getEmail());
response.put(“课程”,student.getCourse());
response.put(“stream”,student.getStream());
response.put(“year”,student.getYear());
response.put(“性别”,student.getGender());
字符串日期=空;
DateFormat df=新的简化格式(“yyyy-MM-dd HH:MM:ss”);
试一试{
date=String.valueOf(df.parse(student.getSignUpDate()).getTime());
}捕获(解析异常){
e、 printStackTrace();
}
答复。付诸表决(“签名更新”,日期);
System.out.println(“响应体::”+Response.toString());
返回响应;
}
您可以在Student类()上返回带有正确Jackson注释的Student(PO)。如果要限制返回的字段,可以添加JsonView注释

public class Student {
  public static class Response {}
  private String firstName;
  private String lastName;
  private String roll;
  private String email;
  private String course;
  private String stream;
  private String year;
  private String gender;

  private Date getSignUpDate;

  @JsonView(Response.class)
  public String getFirstName() {
    return firstName;
  }

  @JsonView(Response.class)
  public String getLastName() {
    return lastName;
  }

  @JsonView(Response.class)
  public String getRoll() {
    return roll;
  }

  @JsonView(Response.class)
  public String getEmail() {
    return email;
  }

  @JsonView(Response.class)
  public String getCourse() {
    return course;
  }

  @JsonView(Response.class)
  public String getStream() {
    return stream;
  }

  @JsonView(Response.class)
  public String getYear() {
    return year;
  }

  @JsonView(Response.class)
  public String getGender() {
    return gender;
  }

  @JsonView(Response.class)
  @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss")
  public Date getGetSignUpDate() {
    return getSignUpDate;
  }
  /// setters are not written.
}


public class StudentCtl {

  @GetMapping(value="/student/{roll}",produces="application/json")
  @ResponseBody
  @JsonView(Student.Response.class)
  private Map<String, Object> getStudentDetails(@PathVariable(value="roll") String roll) {
    return studentDAO.getStudent(roll);
  }
}
公共班级学生{
公共静态类响应{}
私有字符串名;
私有字符串lastName;
私人线轴;
私人字符串电子邮件;
私人弦乐课程;
私有字符串流;
私人弦年;
私人字符串性别;
私人日期更新;
@JsonView(Response.class)
公共字符串getFirstName(){
返回名字;
}
@JsonView(Response.class)
公共字符串getLastName(){
返回姓氏;
}
@JsonView(Response.class)
公共字符串getRoll(){
回程辊;
}
@JsonView(Response.class)
公共字符串getEmail(){
回复邮件;
}
@JsonView(Response.class)
公共字符串getCourse(){
返回路线;
}
@JsonView(Response.class)
公共字符串getStream(){
回流;
}
@JsonView(Response.class)
公共字符串getYear(){
回归年;
}
@JsonView(Response.class)
公共字符串getGender(){
返回性别;
}
@JsonView(Response.class)
@JsonFormat(pattern=“yyyy-MM-dd HH:MM:ss”)
公共日期getSignUpdate(){
返回getSignUpDate;
}
///setter不是书面的。
}
公共班级学生{
@GetMapping(value=“/student/{roll}”,products=“application/json”)
@应答器
@JsonView(Student.Response.class)
私有映射getStudentDetails(@PathVariable(value=“roll”)字符串roll){
返回studentDAO.getStudent(roll);
}
}

您只需从控制器返回student方法,spring将执行封送处理

   @GetMapping(value="/student/{roll}",produces="application/json")
    @ResponseBody
    private Student getStudentDetails(@PathVariable(value="roll") String roll) {
       return studentDAO.getStudent(roll);            
    }
但由于您正在进行日期格式化,我还建议您创建一个单独的类,比如StudentView,并将student映射到StudentView

  class StudentView{
    private String signUpDate;
    ......
    ......
    }
并从控制器返回studentView。所以会是这样的

@GetMapping(value="/student/{roll}",produces="application/json")
@ResponseBody
private StudentView getStudentDetails(@PathVariable(value="roll") String roll) {
   Student student=studentDAO.getStudent(roll);            
   return toStudentView(student);
}

private static StudentView toStudentView(Student stu){
  ......
}

假设您已经有了具有这些属性的学生类。因此,您可以做的是简单地返回对象,如下所示,希望这会起作用

private JSONObject getStudentDetails(@PathVariable(value="roll") String roll) {
    Student student = studentDAO.getStudent(roll);
    System.out.println("Response Body::::: "+response.toString());
    return student ;
}
即使您想更改这些字段的名称,也可以像这样对它们进行注释

class Student {
 @JsonProperty("firstName")
 private String fname;

 @JsonProperty("signUpDate") 
 @JsonFormat(shape=JsonFormat.Shape.STRING, pattern="yyyy-MM-dd HH:mm:ss") 
  private Date date; 
 //getters
 //setters
}

同意@ResponseBody已经隐式地完成了它。不需要在方法中重新实现它。谢谢。只是跟进一下。因此,基本上,这意味着我需要返回对象的映射表示或表示响应的模型,@ResponseBody注释负责从该对象生成JSON响应。正如Tharsan Sivakumar所述,您可以直接使用Student和适当的Jackson注释。返回Student就可以了;)'DateFormat df=新的简化格式(“yyyy-MM-dd HH:MM:ss”);尝试{date=String.valueOf(df.parse(student.getSignUpDate()).getTime();}catch(ParseException e){e.printStackTrace();}'在上面的代码行中,我还在格式化日期,然后返回实际响应。因此,在返回对象之前,最好修改现有的student对象并更改日期。我的意思是,这是好的编程实践还是坏的实践。请原谅一连串的评论;我不熟悉评论和提问,只是开始习惯于评论的语义。自从Jackson v2.0以来,您可以直接在对象成员上使用@JsonFormat注释。因此,你可以在你的学生课堂上自己格式化它,如下所示@JsonProperty(“signUpDate”)@JsonFormat(shape=JsonFormat.shape.STRING,pattern=“yyyy-MM-dd HH:MM:ss”)私有日期;在回答中用格式化的DateThank@Tharsan编辑了上面的学生类。我是否需要在maven中添加Jackson依赖项,因为它不会接受@JsonProperty,或者我的项目有什么问题?