将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 {
        return objectMapper.writeValueAsString(object);
    }

    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;
}

猜你喜欢

转载自www.cnblogs.com/yloved/p/12629407.html