用Jackson实现json和java对象相互转换

java对象不能是内部类

//json字符串转换成java对象

public static <T> T jToO(String json, Class<T> c){
    T o = null;
    try{
        o = new ObjectMapper().readValue(json, c);
    } catch (IOException e){
        // 处理异常
    }
    return o;
}

//调用此方法
Test t = jToO(json, Test.class);

//java对象转换成json字符串
public static String oToJ(Object o){
        ObjectMapper om = new ObjectMapper();
    	Writer w = new StringWriter();
        String json = null;
    	try {
		om.writeValue(w, o);
	    	json = w.toString();
	    	w.close();
		} catch (IOException e) {
		    // 错误处理
		}
		return json;
	}
}

你可能感兴趣的:(Jackson)