首页 > 解决方案 > com.fasterxml.jackson.databind.exc.MismatchedInputException:如何将 React JS 中带有数组字段的对象映射到 Java 对象?

问题描述

当我从客户端向服务器端发出请求时,我传递了具有数组字段的对象。在服务器端,我收到这种类型的错误消息:

Failed to read HTTP message: 
org.springframework.http.converter.HttpMessageNotReadableException: JSON 
parse error: Cannot deserialize instance of `com.example.dto.TopicDto` 
out of START_ARRAY token; nested exception is 
com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot 
deserialize instance of `com.example.dto.TopicDto` out of START_ARRAY token

如何将此对象映射到 Java POJO?我应该在客户端对这个对象使用 JSON.stringify() 或 JSON.parse() 方法吗?

在出现错误之前:缺少必需的请求正文。

我的代码如下:

@Controller
public class TopicController {

@PostMapping(name = "/topic/{forumType}/{jwtToken}")
public ResponseEntity<?> addTopicToForum(@RequestBody TopicDto topicDto, @PathVariable String forumType,
                                         @PathVariable String jwtToken) {
}
}

TopicDto类:

public class TopicDto {

private String title;
private String message;
private int likes;
private String languageForum;
private List<FileDto> files;
// getters and setters, no constructors
}

FileDto 类

public class FileDto {

private String objectId;
private String url;
private Long size;
private String name;
private String type;
// getters and setters, no constructors
}

客户端

class AddTopic extends React.Component {
constructor(props) {
    super(props);

    this.state = {
        title: '',
        message: '',
        isInvalidTitle: false,
        isInvalidMessage: false,
        successFiles: [],
        successNameFiles: [],
        isSuccessUploaded: false,
        isFailureUploaded: false,
        failureNameFiles: []
    }
    this.onSubmitForm = this.onSubmitForm.bind(this);
    this.responseFilestack = this.responseFilestack.bind(this);
}

onSubmitForm(e) {
    e.preventDefault();

    this.validateForm(e);

    if(this.errors.length === 0) {
        let jwtToken = localStorage.getItem("JwtToken");
        let forumType = this.props.match.params.selectedForum;

        const topicDto = {
            title: this.state.title,
            message: this.state.message,
            likes: "0",
            languageForum: forumType,
            files: this.state.successFiles
        }

        fetch(`/topic/${forumType}/${jwtToken}`, {
            method: 'POST',
            body: topicDto,
            headers: {
                'Accept': 'application/json',
                'content-type': 'application/json'
            }
        }).then(response => {
            console.log(response);
        })
    }
}

responseFilestack(response) {
    response.filesUploaded.map((file, index) => {
        const element = {
            objectId: file.uploadId,
            url: file.url,
            size: file.size,
            name: file.originalFile.name,
            type: file.originalFile.type
        };
        this.setState({ 
            successFiles: this.state.successFiles.concat(element),
            successNameFiles: this.state.successNameFiles.concat(file.originalFile.name),
            isSuccessUploaded: true
        });
    });
}
}

更新:请求正文

标签: jsonreactjsspringresttype-mismatch

解决方案


推荐阅读