用Jackson实现json与String之间的转换

  • Post author:
  • Post category:其他


今天学习了Jackson为了日后使用方便,在这做个笔记

其实使用Jackson也很方便:

首先我们导入三个jar包,他们分别是

jackson-core-2.5.3.jar

jackson-annotations-2.5.3.jar

jackson-databind-2.5.3.jar

然后书写代码,书写代码其实只需要两行代码就可以搞定

ObjectMapper mapper = new ObjectMapper();
String result = mapper.writeValueAsString(list);


注意!注意!注意!  writeValueAsString(list)中的list可换成其他对象,如javabean,数组,集合等

下面附上学习时的一个实例代码


Users.java

public class Users {
	private int id;
	private String username;
	private String password;
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}	
}


Test.java

                Users user1 = new Users();
		user1.setId(1);
		user1.setUsername("susu");
		user1.setPassword("123");
		
		Users user2 = new Users();
		user2.setId(2);
		user2.setUsername("tutu");
		user2.setPassword("456");
		
		List<Users> list = new ArrayList<Users>();
		list.add(user1);
		list.add(user2);
		
		ObjectMapper mapper = new ObjectMapper();
		String result = mapper.writeValueAsString(list);
		
		System.out.println(result);

输出结果:

[{"id":1,"username":"susu","password":"123"},{"id":2,"username":"tutu","password":"456"}]



版权声明:本文为loli_kong原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。