JSON解析器的Jackson_java对象转json_List&Map
复杂java对象转换
1.list:数组
@Test public void test3() throws Exception { //创建Person对象 Person p = new Person(); p.setName("张三"); p.setAge(23); p.setGender("男"); p.setBirthday(new Date()); Person p1 = new Person(); p1.setName("张三"); p1.setAge(23); p1.setGender("男"); p1.setBirthday(new Date()); Person p2 = new Person(); p2.setName("张三"); p2.setAge(23); p2.setGender("男"); p2.setBirthday(new Date()); //创建一个List集合 List<Person> ps = new ArrayList<>(); ps.add(p); ps.add(p1); ps.add(p2); //创建Jackson的核心对象 ObjectMapper ObjectMapper mapper = new ObjectMapper(); String json = mapper.writeValueAsString(ps); System.out.println(json); }
2.Map:对象格式一致
@Test public void test4() throws Exception { //创建map对象 HashMap<String, Object> map = new HashMap<String, Object>(); map.put("name","李四"); map.put("age","26"); map.put("gender","男"); //创建Jackson的核心对象 ObjectMapper ObjectMapper mapper = new ObjectMapper(); String json = mapper.writeValueAsString(map); System.out.println(json); }
JSON解析器的Jackson_json转Java对象
1.导入Jackson的相关jar包
2.创建Jackson核心对象 ObjectMapper
3.调用objectMapper的相关方法进行转换
readValue(json字符串数据,Class)
@Test public void test5() throws Exception { //初始化JSON字符串 String json = "{\"gender\":\"男\",\"name\":\"李四\",\"age\":\"26\"}"; //创建ObjectMapper对象 ObjectMapper mapper = new ObjectMapper(); Person person = mapper.readValue(json, Person.class); System.out.println(person); }
搜索
复制
标签:解析器,Jackson,JSON,Person,json,new,ObjectMapper From: https://www.cnblogs.com/pengtianyang/p/16609489.html