Map cannot be cast to com.taotao.pojo.TbContent

解决java.util.LinkedHashMap cannot be cast to com.taotao.pojo.TbContent

Insert picture description here
Because jvm does not know what type of data to return, although you force the returned data, the map data format cannot be directly converted to the data format you want, so similar errors will be reported. You can save the country by curve Learn about.

Because Map can store any data type, in a springboot project I made, the returned data is of type LinkedHashMap, and I want to convert it into TbContent type data.

solution:

It can be converted into LinkedHashMap---->Json---->TbContent type. This way the curve will save the country.
The json format can be converted into any type of data.








The encapsulated JsonUtils package can refer to


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.List;

public class JsonUtils {
    
    

    // 定义jackson对象
    private static final ObjectMapper MAPPER = new ObjectMapper();

    /**
     * 将对象转换成json字符串。
     * <p>Title: pojoToJson</p>
     * <p>Description: </p>
     * @param data
     * @return
     */
    public static String objectToJson(Object data) {
    
    
    	try {
    
    
			String string = MAPPER.writeValueAsString(data);
			return string;
		} catch (JsonProcessingException e) {
    
    
			e.printStackTrace();
		}
    	return null;
    }

    /**
     * 将json结果集转化为对象
     *
     * @param jsonData json数据
     * @return
     */
    public static <T> T jsonToPojo(String jsonData, Class<T> beanType) {
    
    
        try {
    
    
            T t = MAPPER.readValue(jsonData, beanType);
            return t;
        } catch (Exception e) {
    
    
        	e.printStackTrace();
        }
        return null;
    }

    /**
     * 将json数据转换成pojo对象list
     * <p>Title: jsonToList</p>
     * <p>Description: </p>
     * @param jsonData
     * @param beanType
     * @return
     */
    public static <T>List<T> jsonToList(String jsonData, Class<T> beanType) {
    
    
    	JavaType javaType = MAPPER.getTypeFactory().constructParametricType(List.class, beanType);
    	try {
    
    
    		List<T> list = MAPPER.readValue(jsonData, javaType);
    		return list;
		} catch (Exception e) {
    
    
			e.printStackTrace();
		}

    	return null;
    }

}

Guess you like

Origin blog.csdn.net/qq_39095899/article/details/107474235