Created
February 2, 2012 03:04
-
-
Save jteso/1721153 to your computer and use it in GitHub Desktop.
The two most used utility methods to convert Java Pojos from/to Json.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package directlabs.extra; | |
import java.io.StringWriter; | |
import java.io.Writer; | |
import org.codehaus.jackson.map.ObjectMapper; | |
import org.springframework.util.Assert; | |
/** | |
* The two most used utility methods to convert Java Pojos from/to Json. | |
* Depends on Jackson library. | |
* @author jtedilla | |
* @see http://jackson.codehaus.org/ | |
*/ | |
public class JacksonUtils { | |
private static ObjectMapper mapper; | |
static { | |
mapper = new ObjectMapper(); | |
//mapper.getSerializationConfig().setDateFormat(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss")); | |
} | |
public static ObjectMapper getMapper() { | |
return mapper; | |
} | |
public static String toJson(Object object){ | |
Assert.notNull(object, "object cannot be null"); | |
Writer strWriter = new StringWriter(); | |
try { | |
mapper.writeValue(strWriter, object); | |
} catch (Exception e) { | |
throw new RuntimeException("Exception while converting from Java Pojo to Json.", e); | |
} | |
return strWriter.toString(); | |
} | |
public static <T> T fromJson(String json, Class<T> clazz) { | |
try { | |
return (T) mapper.readValue(json, clazz); | |
} catch (Exception e) { | |
throw new RuntimeException("Exception occurred while converting from Json to Java Pojo.", e); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment