今天实训,springboot接受vue axios传来的json字符串对象,想将其转换为Java POJO对象,使用ObjectMapper方式如下:
@RequestMapping(value = "/insertSong", method = RequestMethod.POST)
public String insertSong(@RequestBody String songStr) throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
Song song = mapper.readValue(songStr, Song.class);
int count = musicWebService.insertSong(song);
return count != 0 ? "Success" : "FAIL";
}
报错:
com.fasterxml.jackson.databind.exc.MismatchedInputException:
Cannot construct instance of com.hui.domain.Song
(although at least one Creator exists):
no String-argument constructor/factory method to deserialize from String value
(’{“mid”:"",“musicName”:“1”,“musicSinger”:“1”,“musicLyric”:"",“musicType”:"",“musicImg”:"",“musicUrlID”:“1”,“musicCreationTime”:"",“musicPlayTimes”:0,“musicScore”:10,“musicComment”:“评论”}’)
但是明明我的Song对象有全参构造和无参构造方法
解决:
在POJO对象里加入如下构造方法:
public Song(String json) throws JsonProcessingException {
Song song = new ObjectMapper().readValue(json, Song.class);
this.mid = song.getMid();
this.musicName = song.getMusicName();
this.musicSinger = song.getMusicSinger();
this.musicLyric = song.getMusicLyric();
this.musicType = song.getMusicType();
this.musicImg = song.getMusicImg();
this.musicUrlID = song.getMusicUrlID();
this.musicCreationTime = song.getMusicCreationTime();
this.musicPlayTimes = song.getMusicPlayTimes();
this.musicScore = song.getMusicScore();
this.musicComment = song.getMusicComment();
}
参考:
https://blog.csdn.net/qq_30162239/article/details/86647164