在Java中,我們可以使用Spring框架的@RequestBody
注解來(lái)接收J(rèn)SON數(shù)據(jù)
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
{
"name": "張三",
"age": 30
}
創(chuàng)建一個(gè)名為Person
的Java類:
public class Person {
private String name;
private int age;
// Getter and Setter methods
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
@RequestBody
注解來(lái)接收J(rèn)SON數(shù)據(jù)。例如,創(chuàng)建一個(gè)名為PersonController
的類:import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class PersonController {
@PostMapping("/person")
public String processPerson(@RequestBody Person person) {
return "Name: " + person.getName() + ", Age: " + person.getAge();
}
}
現(xiàn)在,當(dāng)你向/person
發(fā)送一個(gè)包含JSON數(shù)據(jù)的POST請(qǐng)求時(shí),processPerson
方法將會(huì)被調(diào)用,并將JSON數(shù)據(jù)綁定到Person
對(duì)象上。你可以在該方法中處理這些數(shù)據(jù),然后返回一個(gè)響應(yīng)。