java jackson 之间的转换

1. java jackson 转换

  a.需要导入jar


    com.fasterxml.jackson.core
    jackson-core
    2.9.7


    com.fasterxml.jackson.core
    jackson-annotations
    2.9.7


    com.fasterxml.jackson.core
    jackson-databind
    2.9.7

b.相互转换

//数据准备
	List list=new ArrayList();
	list.add(new Student(1,1000d,"旅游",new Date()));
	list.add(new Student(2,1500d,"玩电脑游戏",new Date()));
	list.add(new Student(3,3000d,"看电影",new Date()));
	Student student=new Student(1,1000d,"旅游",new Date());
   //ObjectMapper是JSON操作的核心,Jackson的所有JSON操作都是在ObjectMapper中实现。
	ObjectMapper mapper=new ObjectMapper();
	
	//A.javaBean---->JSON字符串
	    //1.writeValueAsString
	     String json1 = mapper.writeValueAsString(student);
	
	    //2.writeValue
	    StringWriter writer = new StringWriter();
	    mapper.writeValue(writer, student);
	   String string = writer.toString();
	
	//B.JSON字符串----》javaBean
	Student stu = mapper.readValue(json1, Student.class);
	
	  
	//C.list---->JSON字符串
	  String json2 = mapper.writeValueAsString(list);
	  System.out.println(json2);

	 //D.JSON字符串---》list
	     //1.JavaType
	     JavaType javaType = mapper.getTypeFactory().constructParametricType(List.class, Student.class);
	    List stuList=(List) mapper.readValue(json2, javaType);
	    System.out.println(stuList);

          //2.TypeReference
	      List readValue = mapper.readValue(json2, new TypeReference>() {});
	    System.out.println(readValue);
	

 

你可能感兴趣的:(Java)