The entity class Object class into a

rap

Problem Description

When writing controller with SpringBoot, need to accept a map of Object, Object then put into a specific category, as follows:

public boolean postArticle(@RequestBody Map<String, Object> map) {
        ArticleInfo articleInfo = (ArticleInfo) map.get("articleInfo");
        ArticleContent articleContent = (ArticleContent) map.get("articleContent");
        System.out.println(articleInfo + " " + articleContent);
        return true;
}

After the burst exception:

java.lang.ClassCastException: class java.util.LinkedHashMap cannot be cast to class 
cn.zi10ng.blog.domain.ArticleInfo (java.util.LinkedHashMap is in module java.base of loader
 'bootstrap'; cn.zi10ng.blog.domain.ArticleInfo is in unnamed module of loader 
 org.springframework.boot.devtools.restart.classloader.RestartClassLoader @19b54dc3)

problem causes

map is withdrawn Object, not directly into the specific entity class Object

Solution

Json need as an intermediate medium:

   public boolean postArticle(@RequestBody Map<String, Object> map) throws IOException {

        ObjectMapper objectMapper = new ObjectMapper();
        String jsonInfo = objectMapper.writeValueAsString(map.get("articleInfo"));
        String jsonContent = objectMapper.writeValueAsString(map.get("articleContent"));
        ArticleInfo articleInfo = objectMapper.readValue(jsonInfo,ArticleInfo.class);
        ArticleContent articleContent = objectMapper.readValue(jsonContent,ArticleContent.class);

        System.out.println(articleContent + " " +articleInfo);
        return articleService.insertArticle(articleInfo,articleContent);
    }
Published 100 original articles · won praise 142 · views 170 000 +

Guess you like

Origin blog.csdn.net/coder_what/article/details/97901077