使用jackson-mapper-lgpl序列化和反序列化

在前面的博客中说明了json-lib如何序列化和反序列化。现在说明下jackson-mapper-lgpl (以下简称jackson)的用法。

jackson 官网:http://jackson.codehaus.org/

jackson 依赖的jar包:

 maven 依赖配置:

<!-- Json转化模块 -->
		<dependency>
			<groupId>org.codehaus.jackson</groupId>
			<artifactId>jackson-mapper-lgpl</artifactId>
			<version>1.9.9</version>
		</dependency>

 

使用jackson 序列化java对象,即把java对象转化json 字符串

@Test
	public void test_serialize2(){
		ObjectMapper mapper = new ObjectMapper();
		Class2 c=new Class2();
		List<Student>students=new ArrayList<Student>();
		Student student=new Student();
		Map<String, Object> attribute =new HashMap<String, Object>();
		attribute.put("p1", "v1");
		attribute.put("p2", "v2");
		student.setAttribute(attribute);
		students.add(student);
		student.setName("黄威");
		student.setHobby("Roller-Skating");
		c.setStudents(students);
		c.setClassName("计算机0705");
		
		String content;
		try {
			content = mapper.writeValueAsString(student);
			System.out.println(content);
		} catch (JsonGenerationException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

 运行结果:

{"addrr":null,"age":0,"name":"黄威","hobby":"Roller-Skating","attribute":{"p2":"v2","p1":"v1"}}

 

 

使用jackson 反序列化,即把json字符串或inputstream 还原为java对象

@Test
	public void test_reserialize(){
		String jsonInput = "{\"addrr\":{\"country\":\"中国\",\"state\":\"湖北省\",\"street\":\"清河\"},\"age\":25,\"hobby\":\"\",\"name\":\"黄威\"}";
		ObjectMapper mapper = new ObjectMapper();
		Student student;
		try {
			student = mapper.readValue(jsonInput, Student.class);
			System.out.println(student.getAddrr().getStreet());
			System.out.println(student.getName());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

 运行结果:

清河
黄威

 

项目源码见附件

你可能感兴趣的:(json,序列化,反序列化,Jackson,jackson-mapper)