programing

java.util 인터페이스에 대한 기본 또는 기본 생성자를 찾을 수 없습니다.리스트레스트 API Spring 부트

css3 2023. 6. 29. 20:20

java.util 인터페이스에 대한 기본 또는 기본 생성자를 찾을 수 없습니다.리스트레스트 API Spring 부트

저는 다음과 유사한 우체부의 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
}
}

제가 잊어버렸을 때 같은 오류가 있었습니다.@RequestBody파라미터 앞에

  @RequestMapping("/create")
  public Planet create(@RequestBody Planet data) {

당신이 직면한 문제가 무엇인지 이해할 수 없지만, 저는 바로 오류를 볼 수 있기 때문에 그것이 당신이 직면한 문제라고 추측하고 해결책을 제시하려고 합니다.

다음과 같이 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를 한 번만 사용할 수 있으므로 단일을 사용하여 전체 요청 본문을 수신하려면 래퍼 클래스가 필요합니다.@RequestBody주석

@RequestMapping("/create")
  public String create(@RequestBody PlanetData data) {
      Planet mars = planetService.create(data.getName(),data.getArtifacts());
      return mars.toString();
  }

편집 : Planet 클래스를 보니 수정도 필요합니다.

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.

}

이것이 당신의 문제를 해결하기를 바랍니다.

이 대답도 누군가에게 도움이 될 수 있습니다.

API 개발을 위해 스프링 프레임워크를 사용할 때 RequestBody 및 Request에 대해 잘못된 라이브러리를 가져올 수 있습니다.머리글 주석.

저 같은 경우에는 실수로 도서관을 수입했는데,

io.swagger.v3.oas.annotations.parameters.RequestBody

이것은 위와 같은 문제가 발생할 수 있습니다.

올바른 라이브러리를 사용하고 있는지 확인하십시오.

org.springframework.web.bind.annotation.RequestBody

내 생각엔, 전화를 하려는 것 같아요.new List()생성자가 없는.사용해 보십시오.ArrayList당신의 서명으로.

이런 식으로 작동하면 오류를 발견한 것입니다.그런 다음 일반적으로 메서드 서명에서 목록의 구현을 사용하지 않기를 원하기 때문에 호출 메서드의 개념을 다시 생각합니다.

요청 유형이 GET If 유형이 아닌지 확인하십시오. 따라서 데이터를 요청 본문으로 보내지 않는 것이 좋습니다.

당신은 아래와 같이 적어야 합니다:

...
public String create(@RequestBody JSONObject requestParams) {
      String name=requestParams.getString("name");
      List<Planet> planetArtifacts=requestParams.getJSONArray("artifacts").toJavaList(Planet.Class);
...

언급URL : https://stackoverflow.com/questions/54663351/no-primary-or-default-constructor-found-for-interface-java-util-list-rest-api-sp