将java中Map对象转为有相同属性的类对象(json作为中间转换)


java中Map对象转为有相同属性的类对象(json作为中间转换)

  1. 准备好json转换工具类
public class JsonUtil {
    private static ObjectMapper objectMapper = new ObjectMapper();

    public static String objectToString(Object object) throws JsonProcessingException {
        String s;
        if (object instanceof String) {
            s = String.valueOf(object);
        } else {
            s = objectMapper.writeValueAsString(object);
        }
        return s;
    }

    public static <T> T stringToObject(String json,Class<T> object) throws IOException {
        return objectMapper.readValue(json,object);
    }
}
  1. map转为User对象简单示例
public class test {
    public static void main(String[] args) throws IOException {

        Map map=new HashMap();
        map.put("userId",111);
        map.put("userName","张三");
        User user = JsonUtil.stringToObject(JsonUtil.objectToString(map), User.class);
        System.out.println(user);
    }
}

@Data
class User{
    private int userId;
    private String userName;
}


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM