1.json序列化工具
public class JsonUtils { /** * Logger for this class */ private static final Logger logger = LoggerFactory.getLogger(JsonUtils.class); private final static ObjectMapper objectMapper = new ObjectMapper(); static { objectMapper.configure(JsonParser.Feature.ALLOW_COMMENTS, true); objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true); objectMapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true); objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true); objectMapper.configure(JsonParser.Feature.INTERN_FIELD_NAMES, true); objectMapper.configure(JsonParser.Feature.CANONICALIZE_FIELD_NAMES, true); objectMapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false); } private JsonUtils() { } public static String encode(Object obj) { try { return objectMapper.writeValueAsString(obj); } catch (JsonGenerationException e) { logger.error("encode(Object)", e); //$NON-NLS-1$ } catch (JsonMappingException e) { logger.error("encode(Object)", e); //$NON-NLS-1$ } catch (IOException e) { logger.error("encode(Object)", e); //$NON-NLS-1$ } return null; } /** * 将json string反序列化成对象 * * @param json * @param valueType * @return */ public static <T> T decode(String json, Class<T> valueType) { try { return objectMapper.readValue(json, valueType); } catch (JsonParseException e) { logger.error("decode(String, Class<T>)", e); } catch (JsonMappingException e) { logger.error("decode(String, Class<T>)", e); } catch (IOException e) { logger.error("decode(String, Class<T>)", e); } return null; } /** * 将json array反序列化为对象 * * @param json * @param jsonTypeReference * @return */ @SuppressWarnings("unchecked") public static <T> T decode(String json, TypeReference<T> typeReference) { try { return (T) objectMapper.readValue(json, typeReference); } catch (JsonParseException e) { logger.error("decode(String, JsonTypeReference<T>)", e); } catch (JsonMappingException e) { logger.error("decode(String, JsonTypeReference<T>)", e); } catch (IOException e) { logger.error("decode(String, JsonTypeReference<T>)", e); } return null; } }
2.springmvc中自定义JsonConvert
@ControllerAdvice public class MyWebBindingInitializer implements WebBindingInitializer { @Autowired private MappingJackson2HttpMessageConverter jackson2HttpMessageConverter; @InitBinder @Override public void initBinder(WebDataBinder webDataBinder) { webDataBinder.registerCustomEditor(String.class, new StringTrimmerEditor(true)); SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); dateFormat.setLenient(false); webDataBinder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true)); ObjectMapper objectMapper=jackson2HttpMessageConverter.getObjectMapper(); objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); SimpleModule simpleModule = new SimpleModule(); objectMapper.registerModule(simpleModule); objectMapper.configure(JsonParser.Feature.ALLOW_NUMERIC_LEADING_ZEROS, true); } }