今天实训,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

Logo

AtomGit 是由开放原子开源基金会联合 CSDN 等生态伙伴共同推出的新一代开源与人工智能协作平台。平台坚持“开放、中立、公益”的理念,把代码托管、模型共享、数据集托管、智能体开发体验和算力服务整合在一起,为开发者提供从开发、训练到部署的一站式体验。

更多推荐