헤르미온느 그레인저 :
나는이 유사 우편 배달부의 POST 요청에 요청 본문을 전달하고있다 :
"name":"Mars",
"artifacts":[
{
"elements":[
{
"name":"carbon",
"amount":0.5,
"measurement":"g"
}
],
"typeName":"typeA"
},
{
"elements":[
{
"name":"hydrogen",
"amount":0.2,
"measurement":"g"
}
],
"typeName":"typeB"
}
]
이 같은 나머지 컨트롤러 외모의 방법을 만들 수 있습니다.
@RequestMapping("/create")
public Planet create(@RequestBody Planet data) {
Planet mars = planetService.create(data.getName(),data.getArtifacts());
return mars;
행성과 모든 중첩 된 객체는 기본 생성자 등이있다 :
public Planet() {}
그러나, 나는 때문에 기본 생성자의 부족으로 새로운 행성 개체를 만들 수 없습니다입니다. 도와주세요!
편집 : 행성의 클래스
public class Planet {
@JsonProperty("name")
private String name;
@Field("artifacts")
private List<Artifact> artifacts;
public Planet() {}
public Planet(String name, List<Artifact> artifacts)
{
this.name = name;
this.artifacts = artifacts;
}
//setters and getters
}
아티팩트 클래스 :
public class Artifact() {
@Field("elements")
private List<Element> elements;
@JsonProperty("typeName")
private String typeName;
public Artifact() {}
public Artifact(String typeName, List<Element> elements)
{
this.typeName = typeName;
this.elements = elements;
}
}
요소 클래스 :
public class Element() {
@JsonProperty("elementName")
private String name;
@JsonProperty("amount")
private double amount;
@JsonProperty("measurement")
private String measurement;
public Element() {}
public Element(String name, double amount, String measurement)
{
//assignments
}
}
Arpit 아그라 왈 :
난 당신이 직면하고있는 문제가 무엇인지 이해하지 않지만, 내가 바로 그 추측하는 것은 당신이 직면하고있는 문제 때문에 오류를 볼 수있다, 나는 당신에게 솔루션을 제공하기 위하여려고하고있다.
이처럼 JSON 데이터 구조와 일치하는 클래스를 만듭니다 :
Class PlanetData {
private String name;
private List<Planet> artifacts;
public PlanetData(String name, List<Planet> artifacts){
name = name;
artifacts = artifacts;
}
// include rest of getters and setters here.
}
그런 다음 컨트롤러는 다음과 같아야합니다. 기본적으로 당신은 넣어 필요 @RequestBody
하면 요청 JSON에서받을하려는 모든 매개 변수. 이전 만 넣어 @RequestBody
당신이 하나를 사용하여 전체 요청 본문을받을 수있는 래퍼 클래스가 필요하므로, 이름 매개 변수없는 유물 매개 변수 및 요청 바디는 한 번만 소비 할 수 있기 때문에 @RequestBody
주석을.
@RequestMapping("/create")
public String create(@RequestBody PlanetData data) {
Planet mars = planetService.create(data.getName(),data.getArtifacts());
return mars.toString();
}
편집 : 지구 클래스를 보면, 그것은 또한 약간의 수정이 필요
public class Planet {
private String typeName; // key in json should match variable name for proper deserialization or you need to use some jackson annotation to map your json key to your variable name.
private List<Element> elements;
public Planet() {}
public Planet(String typeName, List<Element> elements)
{
this.typeName = typeName;
this.elements = elements;
}
//setters and getters. Remember to change your setters and getter from name to typeName.
}
이 문제를 해결 바랍니다.