Here you can find the source of toJson(Object object)
Parameter | Description |
---|---|
object | to be converted |
public static String toJson(Object object)
//package com.java2s; //License from project: Apache License import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; public class Main { private static final ThreadLocal<ObjectMapper> tlObjectMapper = new ThreadLocal<ObjectMapper>() { @Override/*from w w w . j av a 2s . c o m*/ protected ObjectMapper initialValue() { return new ObjectMapper(); } }; /** * Converts object to JSON string * * @param object to be converted * @return JSON representation of object */ public static String toJson(Object object) { try { return getObjectMapper().writeValueAsString(object); } catch (JsonProcessingException e) { throw new IllegalArgumentException( "Given Object could not be serialized to JSON. Error: " + e.getMessage()); } } /** * Allows JSON serialization with custom mapping * * @param object to be serialized * @param customMapper custom mapper * @return JSON representation of object */ public static String toJson(Object object, ObjectMapper customMapper) { if (customMapper == null) { throw new IllegalArgumentException("Missing custom mapper!"); } try { return customMapper.writeValueAsString(object); } catch (JsonProcessingException e) { throw new IllegalArgumentException( "Given Object could not be serialized to JSON. Error: " + e.getMessage()); } } /** * Returns a thread-local instance of JSON ObjectMapper. * * @return ObjectMapper. */ public static ObjectMapper getObjectMapper() { return tlObjectMapper.get(); } }