Java tutorial
/* * Copyright 2005-2013 iterzp.com. All rights reserved. * Support: http://www.iterzp.com * License: http://www.iterzp.com/license */ package com.iterzp.momo.utils; import java.io.IOException; import java.io.Writer; import org.springframework.util.Assert; import org.codehaus.jackson.JsonGenerationException; import org.codehaus.jackson.map.JsonMappingException; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.type.JavaType; import org.codehaus.jackson.type.TypeReference; /** * Utils - JSON * * @author yd14 Team * @version 3.0 */ public final class JsonUtils { /** ObjectMapper */ private static ObjectMapper mapper = new ObjectMapper(); /** * ?? */ private JsonUtils() { } /** * ?JSON * * @param value * * @return JSOn */ public static String toJson(Object value) { try { return mapper.writeValueAsString(value); } catch (Exception e) { e.printStackTrace(); } return null; } /** * JSON? * * @param json * JSON * @param valueType * * @return */ public static <T> T toObject(String json, Class<T> valueType) { Assert.hasText(json); Assert.notNull(valueType); try { return mapper.readValue(json, valueType); } catch (Exception e) { e.printStackTrace(); } return null; } /** * JSON? * * @param json * JSON * @param typeReference * * @return */ public static <T> T toObject(String json, TypeReference<?> typeReference) { Assert.hasText(json); Assert.notNull(typeReference); try { return mapper.readValue(json, typeReference); } catch (Exception e) { e.printStackTrace(); } return null; } /** * JSON? * * @param json * JSON * @param javaType * * @return */ public static <T> T toObject(String json, JavaType javaType) { Assert.hasText(json); Assert.notNull(javaType); try { return mapper.readValue(json, javaType); } catch (Exception e) { e.printStackTrace(); } return null; } /** * ?JSON? * * @param writer * writer * @param value * */ public static void writeValue(Writer writer, Object value) { try { mapper.writeValue(writer, value); } catch (JsonGenerationException e) { e.printStackTrace(); } catch (JsonMappingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }