Json字符串转对象,使用ObjectMapper方式报错:no String-argument constructor/factory method
今天實訓,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
總結
以上是生活随笔為你收集整理的Json字符串转对象,使用ObjectMapper方式报错:no String-argument constructor/factory method的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 网络前缀长度指的是什么意思
- 下一篇: Sysmon占用CPU及内存过高问题分析