json - 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
});
});
}
}
解决方案
推荐阅读
- java - 使用简单代码在 Java 或 Python 上创建沙漏模式?
- sql-server - 通过 SSMS 编辑 dtsx
- python-3.x - 将项目的根目录设置为python路径
- html - CSS Grid 容器未以浏览器视口为中心
- javascript - 在 nuxt 中使用 babel-polyfill(而不是 polyfill.io)
- node.js - 有没有办法永久缓存客户端计算机中的文件?
- python - 有没有办法在 Kivy 中使用 id 访问其他类对象?
- sql - ORA-01722: 无效号码 #time
- c++ - NAPI AsyncWorker:将指针数组转换为 Napi::Array 而不使用 big for?
- python - ImportError:无法导入名称“model_to_dot”