package com.hcks.cmfds.commons.util; import java.text.SimpleDateFormat; import java.util.HashMap; import java.util.List; import java.util.Map; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.map.SerializationConfig; import com.hcks.cmfds.commons.lang.PaginationList; /** * * @Author 刘厦(liusha.information@gmail.com) * @Date 创建时间:May 16, 2011 13:08:19 PM * @Version 0.0.0 */ public class JsonUtils { private static ObjectMapper mapper = new ObjectMapper(); public static final String SIMPLE_DATETIME_FORMAT = "yyyy-MM-dd HH:mm:ss"; public static final SimpleDateFormat df = new SimpleDateFormat(SIMPLE_DATETIME_FORMAT); static { mapper.configure(org.codehaus.jackson.map.SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS, false); mapper.configure(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS, false); mapper.getSerializationConfig().setDateFormat(df); } public static ObjectMapper getMapperBinder(){ return mapper; } /** * 将各种形式转换为json格式 * @param object * @return */ public static String toJson(Object object) { try { return mapper.writeValueAsString(object); } catch (Exception e) { throw new RuntimeException(e); } } /** * 将json串 转换为已知对象 * @param json * @param clazz * @return */ public static Object fromJson(String json, Class clazz) { try { return mapper.readValue(json, clazz); } catch (Exception e) { throw new RuntimeException(e); } } /** * 转换为grid数据 * @param data * @param page * @return */ @SuppressWarnings("unchecked") public static String wrapListForGrid(List data, int page) { if (page <= 0) page = 1; Map map = new HashMap(3); map.put("page", page); map.put("rows", data); if (data instanceof PaginationList) { map.put("total", ((PaginationList)data).getTotal()); } else { map.put("total", data.size()); } return toJson(map); } public static String getJsons(Object object) { ObjectMapper mappers = new ObjectMapper(); String SIMPLE_DATETIME_FORMAT = "yyyy-MM-dd"; SimpleDateFormat df = new SimpleDateFormat(SIMPLE_DATETIME_FORMAT); mappers.configure(org.codehaus.jackson.map.SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS, false); mappers.configure(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS, false); mappers.getSerializationConfig().setDateFormat(df); try { return mappers.writeValueAsString(object); } catch (Exception e) { throw new RuntimeException(e); } } /** * 转换为grid数据 * @param data * @param page * @return */ @SuppressWarnings("unchecked") public static String wrapListForGrid(List data, int page,List vos) { if (page <= 0) page = 1; Map map = new HashMap(3); map.put("page", page); map.put("rows", vos); if (data instanceof PaginationList) { map.put("total", ((PaginationList)data).getTotal()); } else { map.put("total", data.size()); } return toJson(map); } }