java中json字符串与java对象相互转换的简单使用

public class Demo {
	public static void main(String[] args) throws JsonGenerationException, JsonMappingException, IOException {
		//javaBeanToJsonStr();
		//mapToJsonStr();
		//listToJsonStr();
		jsonStrToJavaBean();
	}

	/**
	 * 对象转json字符串
	 * @throws IOException
	 * @throws JsonGenerationException
	 * @throws JsonMappingException
	 */
	private static void javaBeanToJsonStr() throws IOException, JsonGenerationException, JsonMappingException {
		//使用jackson实现java对象与json对象的相互转换
		//1.导入jar包jackson-core-asl-1.9.13.jar和jackson-mapper-asl-1.9.13.jar
		//2.创建一个数据模型Book 就是一个javaBean
		Book book = new Book("1001","百年孤独",16,100,"文学","魔幻现实主义");
		//创建 一个映射对象ObjectMapper
		ObjectMapper mapper = new ObjectMapper();
		//3.把对象转成Json格式字符串
		String jsonStr1 = mapper.writeValueAsString(book);
		System.out.println(jsonStr1);
		//{"id":"1001","name":"百年孤独","price":16.0,"pnum":100,"category":"文学","description":"魔幻现实主义"}
	}
	
	/**
	 * map转json字符串
	 * @throws JsonGenerationException
	 * @throws JsonMappingException
	 * @throws IOException
	 */
	public static void mapToJsonStr() throws JsonGenerationException, JsonMappingException, IOException {
		// TODO Auto-generated method stub
		//创建一个map对象
		Map<String, String> map = new HashMap<String, String>();
		map.put("You", "Need");
		map.put("To", "Go");
		ObjectMapper mapper = new ObjectMapper();
		String mapJsonStr = mapper.writeValueAsString(map);
		System.out.println(mapJsonStr);
	}
	
	/**
	 * 集合转为字符串
	 * @throws JsonGenerationException
	 * @throws JsonMappingException
	 * @throws IOException
	 */
	public static void listToJsonStr() throws JsonGenerationException, JsonMappingException, IOException {
		List<Book> list = new ArrayList<Book>();
		list.add(new Book("1001","百年孤独",16,100,"文学","魔幻现实主义"));
		list.add(new Book("1002","人生",16,100,"文学","讽刺"));
		list.add(new Book("1001","红与黑",16,100,"文学","现实主义"));
		ObjectMapper mapper = new ObjectMapper();
		String listJsonStr = mapper.writeValueAsString(list);
		System.out.println(listJsonStr);
		//[{"id":"1001","name":"百年孤独","price":16.0,"pnum":100,"category":"文学","description":"魔幻现实主义"},
		//{"id":"1002","name":"人生","price":16.0,"pnum":100,"category":"文学","description":"讽刺"},
		//{"id":"1001","name":"红与黑","price":16.0,"pnum":100,"category":"文学","description":"现实主义"}]
	}
	
	public static void jsonStrToJavaBean() throws JsonParseException, JsonMappingException, IOException {
		String jsonStr = "{\"id\":\"1001\",\"name\":\"百年孤独\",\"price\":16.0,\"pnum\":100,\"category\":\"文学\",\"description\":\"魔幻现实主义\"}";
		//System.out.println(jsonStr);
		
		//把字符串转成对象
		ObjectMapper mapper = new ObjectMapper();
		//其内部会调用无参构造方法,因此需要在Book类中声明无参构造方法
		Book book = mapper.readValue(jsonStr, Book.class);
		System.out.println(book);
	}
}

发布了33 篇原创文章 · 获赞 6 · 访问量 1709

猜你喜欢

转载自blog.csdn.net/EEEEEEcho/article/details/104334745