com.fasterxml.jackson.databind.exc.MismatchedInputException: Как отобразить объект с полем массива в React JS на объект Java? - PullRequest
0 голосов
/ 23 сентября 2019

Когда я делаю запрос от клиентской стороны к серверной, я передаю объект, у которого есть поле с массивом.На стороне сервера я получаю сообщение об ошибке такого типа:

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 class:

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 class

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
        });
    });
}
}

ОБНОВЛЕНИЕ: request body

...