將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