使用邮递员解析和映射json

时间:2019-01-29 14:02:16

标签: java spring-boot spring-restcontroller

@Controller
public class StudentRegistrationController {

@RequestMapping(method = RequestMethod.POST, value="/register/reg")
@ResponseBody
StudentRegistrationReply registerStudent(@RequestBody Student student) {
    System.out.println("In registerStudent");
    StudentRegistrationReply stdregreply = new StudentRegistrationReply();           

    StudentRegistration.getInstance().add(student);

    //We are setting the below value just to reply a message back to the caller
    stdregreply.setId(student.getId());
    stdregreply.setName(student.getName());
    stdregreply.setAge(student.getAge());
    stdregreply.setRegistrationNumber(student.getRegistrationNumber());
    stdregreply.setPayment_detailsList(student.getPayment_detailsList());
    stdregreply.setRegistrationStatus("Successful");

    daocontroller.setStudentRegistration(stdregreply);
    return stdregreply;

}

}

试图将邮递员请求映射到但为空

json就像

{ 
    "id": 300,
    "name": "kukri",
    "age": 26,
    "registrationNumber": "54326",
    "Student_payment_details":
    {
      "pay": 50000,
      "date": "23061994",
      "phcounter": "SKB"
    }

}

Java类

public class Student {
    private int id;
    private String name;
    private int age;
    private String registrationNumber;
    private Student_payment_details payment_detailsList; //getter and setter
}

1 个答案:

答案 0 :(得分:2)

  1. 使用Lombok作为我的getter / setter,您可以忽略它并编写自己的getter / setters
  2. 您的请求的主体存在问题,您应该将json中的键作为Java变量名称进行传递,您传递的是Student_payment_details而不是payment_detailsList
  3. 字母和字母的设置应该与您的变量名有关。

请求网址:

curl -X POST \
  http://localhost:8080/register/reg \
  -H 'Content-Type: application/json' \
  -H 'cache-control: no-cache' \
  -d '{
  "id": 300,
  "name": "kukri",
  "age": 26,
  "registrationNumber": "54326",
  "payment_detailsList": {
    "pay": 50000,
    "date": "23061994",
    "phcounter": "SKB"
  }
}'

Java Dtos:

import lombok.Data;

@Data
public class Student_payment_details {
    int pay;
    String date;
    String phcounter;
}

import lombok.Data;

@Data
public class Student {
    private int id;
    private String name;
    private int age;
    private String registrationNumber;
    private Student_payment_details payment_detailsList; //getter and setter
}

下图显示了控制器内部填充的学生变量的内容

enter image description here

注意: 我不知道您的用例,但作为一般建议,请遵循一种命名约定,snake_casecamelCase
在Java中,最常用的是camelCase
同样,变量的命名应类似于类类型,
这里的变量payment_detailsList的类型为Student_payment_details,这会引起混淆,如果您希望JSON变量名不同,则可以将其用作

 @JsonProperty("payment_detailsList")
 private Student_payment_details student_payment_details;