ObjectMapper json转换

objectMapper json转换

maven引入

jackson-databind 

object -> json

 mapper.writeValueAsString(obj);

json -> object

mapper.readValue(json,valueType);

jsonUtil

public class JSONUtil {
    private static ObjectMapper objectMapper=new ObjectMapper();
    public static String  toJson(Object obj1){
        try {
            return objectMapper.writeValueAsString(obj1);
        } catch (JsonProcessingException e) {
            System.out.println("json转换异常");
        }
        return null;
    }

    public static Object parseObject(String jsonStr,Class targetClass){
        try {
           return   objectMapper.readValue(jsonStr,targetClass);
        } catch (IOException e) {
            System.out.println("json转换异常");
        }
        return null;
    }

}

JSONMain

public class JSONMain {
    public static void main(String[] args) {
        List studentList=new ArrayList<>();
        studentList.add(new Student(1L,"王磊"));
        studentList.add(new Student(2L,"张三"));
        String studentListJsonStr=JSONUtil.toJson(studentList);
        System.out.println("jsonStr:"+studentListJsonStr);
       List students= (List) JSONUtil.parseObject(studentListJsonStr,List.class);
        System.out.println("列表第一个student:"+students.get(0));
    }


    public static class Student{
        private String name;
        private Long id;

        public Student() {
        }

        public Student(Long id,String name) {
            this.name = name;
            this.id = id;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public Long getId() {
            return id;
        }

        public void setId(Long id) {
            this.id = id;
        }

        @Override
        public String toString() {
            return "Student{" +
                    "name='" + name + '\'' +
                    ", id=" + id +
                    '}';
        }
    }
}


输出结果

jsonStr:[{"name":"王磊","id":1},{"name":"张三","id":2}]
列表第一个student:{name=王磊, id=1}

你可能感兴趣的:(java)