猿问

使用邮递员解析和映射 json

@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

}


江户川乱折腾
浏览 108回答 1
1回答

萧十郎

使用 Lombok 作为我的 getter/setter,您可以忽略它并编写自己的 getter/setter您的请求正文存在问题,您应该将 json 中的密钥作为 java 变量名传递,您正在传递Student_payment_details而不是payment_detailsListGetters 和 Setters 应该与你的变量名有关。请求网址: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;@Datapublic class Student_payment_details {    int pay;    String date;    String phcounter;}import lombok.Data;@Datapublic class Student {    private int id;    private String name;    private int age;    private String registrationNumber;    private Student_payment_details payment_detailsList; //getter and setter}下图显示了控制器内填充的学生变量的内容注意:我不知道您的用例,但作为一般建议,请遵循 1 种命名约定,snake_case或camelCase.在 java 中主要使用的是camelCase.变量的命名也应该与类类型相似,这里变量 payment_detailsList 的类型Student_payment_details会导致混淆,如果您希望 JSON 变量名称不同,则可以使用 as @JsonProperty("payment_detailsList") private Student_payment_details student_payment_details;
随时随地看视频慕课网APP

相关分类

Java
我要回答