Json字符串转对象,使用ObjectMapper方式报错:no String-argument constructor/factory method

Posted 莉妮可丝的猫

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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的主要内容,如果未能解决你的问题,请参考以下文章

Json字符串转对象,使用ObjectMapper方式报错:no String-argument constructor/factory method

Json字符串转对象,使用ObjectMapper方式报错:no String-argument constructor/factory method

Json字符串转对象,使用ObjectMapper方式报错:no String-argument constructor/factory method

Json字符串转对象,使用ObjectMapper方式报错:no String-argument constructor/factory method

ObjectMapper的使用

ObjectMapper将json转对象报错处理