简体   繁体   中英

Spring MVC @requestbody json one argument problem

I have incomprehensible problem with Spring MVC in my REST API app. I created POJO java class with only one field and also controller with @RequestBody annotation:

    @PostMapping ("/add")
    ResponseEntity<ResponseDetails> save(@Valid @RequestBody CategoryDTO categoryDTO) {
        Category category = categoryService.save(categoryDTO);
        URI location = ServletUriComponentsBuilder.fromCurrentRequest()
                .path("/{id}")
                .buildAndExpand(category.getId())
                .toUri();

        return ResponseEntity.created(location).build();
    }

POJO class with field "name":

@Value
@Builder
public class CategoryDTO {
    @NotNull(message = MessageContent.VALID_NOT_NULL)
    @NotBlank(message = MessageContent.VALID_NOT_BLANK)
    @Size(max = 50, message = MessageContent.VALID_MAX_SIZE + 50)
    @JsonProperty("name")
    String name;
}

Problem shows up when I sending json request:

{   
    "name": "22"
}

Result of this request is exception:

2021-01-21 14:42:38.917  WARN 11084 --- [nio-8080-exec-2] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot construct instance of `pl.pg.funfactsrap.category.dto.CategoryDTO` (although at least one Creator exists): cannot deserialize from Object value (no delegate- or property-based Creator); nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of `pl.pg.funfactsrap.category.dto.CategoryDTO` (although at least one Creator exists): cannot deserialize from Object value (no delegate- or property-based Creator)
 at [Source: (PushbackInputStream); line: 2, column: 5]]

There is no exception when I am sending json with two or more arguments. Any idea? Thanx.

Here is my pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.4.1</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>pl.pg</groupId>
    <artifactId>funfactsrap</artifactId>
    <version>1.0.0</version>
    <name>Fun Facts RAP</name>
    <description></description>

    <properties>
        <java.version>11</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>com.github.javafaker</groupId>
            <artifactId>javafaker</artifactId>
            <version>1.0.2</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>6.1.5.Final</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.7.0</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.7.0</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

That's work fine (below):

@Value
@Builder
public class CategoryDTO {
    @NotNull(message = MessageContent.VALID_NOT_NULL)
    @NotBlank(message = MessageContent.VALID_NOT_BLANK)
    @Size(max = 50, message = MessageContent.VALID_MAX_SIZE + 50)
    @JsonProperty("name")
    String name;

    String test;
}

You need a constructor with all parameters:

public CategoryDTO(String name) {
    this.name = name;
}

Or using @AllArgsConstructor or @Data from lombok.

This is solution

public class CategoryDTO {
@NotNull(message = MessageContent.VALID_NOT_NULL)
@NotBlank(message = MessageContent.VALID_NOT_BLANK)
@Size(max = 50, message = MessageContent.VALID_MAX_SIZE + 50)
String name;
//String test;

@JsonCreator
public CategoryDTO(String name) {
    this.name = name;
}

public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}

}

I removed the @Value annotation and explicitly declared setters/getters and the constructor with @JsonCreator annotation. Thanx for help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM