java jackson的使用

Maven项目请导入以下信息:


				    org.jboss.resteasy
				    resteasy-jackson-provider
				
  
		    com.fasterxml.jackson.core  
		    jackson-annotations  
		
 
  

 非Maven项目请导入: 
  

jackson-core-asl-1.9.4.jar

jackson-mapper-asl-1.9.4.jar

jackson-jaxrs-1.9.4.jar

jackson-xc-1.9.12.jar

1.对象转json

/**
	 * 对象转json
	 * @param obj object 对象
	 * @return String
	 * @throws IOException
	 */
	public static String BeanToJson(Object obj) throws IOException { 
		
        ObjectMapper mapper = new ObjectMapper();  
        StringWriter sw = new StringWriter();  
        JsonGenerator gen = new JsonFactory().createJsonGenerator(sw);  
        mapper.writeValue(gen, obj);  
        gen.close();  
        return sw.toString();  
    }

2.Json转对象

/**
	 * json转对象
	 * @param jsonStr json字符串
	 * @param objClass 类名.class
	 * @return 泛型
	 * @throws Exception
	 */
	public static  T jsonToBean(String jsonStr, Class objClass)  
            throws Exception {
		
        ObjectMapper mapper = new ObjectMapper(); 
        
        return mapper.readValue(jsonStr, objClass);  
    }


你可能感兴趣的:(json)