gpt4 book ai didi

java - 使用 postman 解析和映射 json

转载 作者:行者123 更新时间:2023-12-02 01:41:16 25 4
gpt4 key购买 nike

@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;

}

}

尝试将 postman 请求映射到但得到空

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. 使用 Lombok 作为我的 getter/setter,您可以忽略它并编写自己的 getter/setter
  2. 您的请求正文有问题,您应该将 json 中的 key 作为 java 变量名称传递,您传递的是 Student_ payment_details 而不是 payment_detailsList
  3. Getter 和 Setter 应该与您的变量名称相关。

请求网址:

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
}

下图显示了 Controller 内填充的学生变量的内容

enter image description here

注意:我不知道您的用例,但作为一般建议,请遵循 1 种命名约定:snake_casecamelCase
在java中最常用的是camelCase
另外变量的命名应该与类类型类似,
这里变量 payment_detailsList 的类型是 Student_ payment_details ,这会导致困惑,如果你希望 JSON 变量名称不同,那么你可以使用 as

 @JsonProperty("payment_detailsList")
private Student_payment_details student_payment_details;

关于java - 使用 postman 解析和映射 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54422793/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com