Jackson的简单使用

Jackson既可以将对象转化为jason格式,又可以将jason字符串转化为java对象。他的效率要比xstream高,因为他是单例的。

首先,我们创建两个对象,以便jackson来使用:

public class User {
    private int id;
    private String username;
    private String password;
    private Group group;
    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;
    }
    public Group getGroup() {
        return group;
    }
    public void setGroup(Group group) {
        this.group = group;
    }

    public User() {
    }

    public User(int id, String username, String password, Group group) {
        super();
        this.id = id;
        this.username = username;
        this.password = password;
        this.group = group;
    }

    public User(int id, String username, String password) {
        super();
        this.id = id;
        this.username = username;
        this.password = password;
    }
}

public class Group {
    private int id;
    private String name;
    List<User> users;

    public void addUser(User u) {
        if(users==null) {
            users = new ArrayList<User>();
        }
        users.add(u);
    }

    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Group(int id, String name) {
        super();
        this.id = id;
        this.name = name;
    }

    public Group() {
    }

}


下面通过代码和注释来讲解jackson的简单使用

<span style="white-space:pre">	</span>@Test
	public void test01() {
		StringWriter out = new StringWriter();
		JsonGenerator jg = null;
		try {
			//1、创建JsonFactory
			JsonFactory jf = new JsonFactory();
			//2、创建JsonGenerator
			jg = jf.createJsonGenerator(out);
			//使用一种相对漂亮的格式输出
			jg.useDefaultPrettyPrinter();
			//3、创建ObjectMapper,通过ObjectMapper来写对象
			User u = new User(1,"劳动法","123",new Group(1,"财务处"));
			ObjectMapper mapper = new ObjectMapper();
			mapper.writeValue(jg, u);
			System.out.println(out.toString());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				if(jg!=null) jg.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	@Test
	public void test02() {
		StringWriter out = new StringWriter();
		JsonGenerator jg = null;
		try {
			//1、创建JsonFactory
			JsonFactory jf = new JsonFactory();
			//2、创建JsonGenerator
			jg = jf.createJsonGenerator(out);
			//使用一种相对漂亮的格式输出
//			jg.useDefaultPrettyPrinter();
			//3、创建ObjectMapper,通过ObjectMapper来写对象
			List<User> us = new ArrayList<User>();
			User u = new User(1,"劳动法","123",new Group(1,"财务处"));
			us.add(u);
			u = new User(2,"猪八戒","123",new Group(1,"财务处"));
			us.add(u);
			u = new User(3,"张学友","123",new Group(2,"教务处"));
			us.add(u);
			ObjectMapper mapper = new ObjectMapper();
			mapper.writeValue(jg, us);
			System.out.println(out.toString());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				if(jg!=null) jg.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	@Test
	public void test02_1() {
		List<User> us = new ArrayList<User>();
		User u = new User(1,"劳动法","123",new Group(1,"财务处"));
		us.add(u);
		u = new User(2,"猪八戒","123",new Group(1,"财务处"));
		us.add(u);
		u = new User(3,"张学友","123",new Group(2,"教务处"));
		us.add(u);
		System.out.println(JsonUtil.getInstance().obj2json(us));
	}
	
	@Test
	public void test03() {
		try {
			String json = "{\"id\":1,\"username\":\"杂货\",\"password\":\"123\",\"group\":{\"id\":1,\"name\":\"财务处\"}}";
			ObjectMapper mapper = new ObjectMapper();
			User u = mapper.readValue(json, User.class);
			System.out.println(u.getId()+","+u.getUsername()+","+u.getGroup().getName());
		} catch (JsonParseException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	@Test
	public void test04() {
		try {
			String json = "[{\"id\":1,\"username\":\"劳动法\",\"password\":\"123\",\"group\":{\"id\":1,\"name\":\"财务处\"}},{\"id\":2,\"username\":\"猪八戒\",\"password\":\"123\",\"group\":{\"id\":1,\"name\":\"财务处\"}},{\"id\":3,\"username\":\"张学友\",\"password\":\"123\",\"group\":{\"id\":2,\"name\":\"教务处\"}}]";
			ObjectMapper mapper = new ObjectMapper();
			//在把json转换为list的时候,不能直接存储Bean对象,list中存储的是Map对象
			/*List<User> us = mapper.readValue(json,List.class);
			for(User u:us) {
				System.out.println(u.getUsername());
			}*/
			/**
			 * 所以的json都是通过map来存储的,不会直接存储bean,但是在开发中,把字符串转换为对象
			 * 一般只会对单个的对象转换,很少会用到对对象的完全转换
			 */
			List<Map<String,Object>> us = mapper.readValue(json, List.class);
			for(Map<String,Object> m:us) {
				System.out.println(m.get("id"));
				System.out.println(m.get("group"));
			}
		} catch (JsonParseException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}
	
	@Test
	public void test05() {
		try {
			String json = "[{\"id\":1,\"username\":\"劳动法\",\"password\":\"123\",\"group\":{\"id\":1,\"name\":\"财务处\"}},{\"id\":2,\"username\":\"猪八戒\",\"password\":\"123\",\"group\":{\"id\":1,\"name\":\"财务处\"}},{\"id\":3,\"username\":\"张学友\",\"password\":\"123\",\"group\":{\"id\":2,\"name\":\"教务处\"}}]";
			ObjectMapper mapper = new ObjectMapper();
			/*
			 * 在Jaskson中提供了一种基于节点的读取方法
			 */
			JsonNode node = mapper.readTree(json);
			//判断这个节点是否是数组
			System.out.println(node.isArray());
			System.out.println(node.size());
			System.out.println(node.get(0).get("username"));
			System.out.println(node.get(0).get("group").get("name"));
		} catch (JsonParseException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

我们通过上述代码已经简单了解了jackson的使用,根据上述代码,我们可以构造一个jackson的util类,来更方便的使用他。上述代码中的test02_1也用到了此类。

public class JsonUtil {
	private static JsonUtil ju;
	private static JsonFactory jf;
	private static ObjectMapper mapper;
	private JsonUtil(){}
	
	public static JsonUtil getInstance() {
		if(ju==null) ju = new JsonUtil();
		return ju;
	}
	
	public static ObjectMapper getMapper() {
		if(mapper==null) {
			mapper = new ObjectMapper();
		}
		return mapper;
	}
	
	public static JsonFactory getFactory() {
		if(jf==null) jf = new JsonFactory();
		return jf;
	}
	
	public String obj2json(Object obj) {
		JsonGenerator jg = null;
		try {
			jf = getFactory();
			mapper = getMapper();
			StringWriter out = new StringWriter();
			jg = jf.createJsonGenerator(out);
			mapper.writeValue(jg, obj);
			return out.toString();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if(jg!=null) jg.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}
	
	public Object json2obj(String json,Class<?> clz) {
		try {
			mapper = getMapper();
			return mapper.readValue(json,clz);
		} catch (JsonParseException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
}



你可能感兴趣的:(java,Jackson,Jason)