[color=violet][size=large]
public class JsonBinder { private static Logger logger = LoggerFactory.getLogger(JsonBinder.class); private ObjectMapper mapper; public JsonBinder(Inclusion inclusion) { mapper = new ObjectMapper(); //设置输出包含的属性 mapper.getSerializationConfig().setSerializationInclusion(inclusion); //设置输入时忽略JSON字符串中存在而Java对象实际没有的属性 mapper.getDeserializationConfig().set( org.codehaus.jackson.map.DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false); } /** * 创建输出全部属性到Json字符串的Binder. */ public static JsonBinder buildNormalBinder() { return new JsonBinder(Inclusion.ALWAYS); } /** * 创建只输出非空属性到Json字符串的Binder. */ public static JsonBinder buildNonNullBinder() { return new JsonBinder(Inclusion.NON_NULL); } /** * 创建只输出初始值被改变的属性到Json字符串的Binder. */ public static JsonBinder buildNonDefaultBinder() { return new JsonBinder(Inclusion.NON_DEFAULT); } /** * 如果JSON字符串为Null或"null"字符串,返回Null. * 如果JSON字符串为"[]",返回空集合. * * 如需读取集合如List/Map,且不是List<String>这种简单类型时使用如下语句: * List<MyBean> beanList = binder.getMapper().readValue(listString, new TypeReference<List<MyBean>>() {}); */ public <T> T fromJson(String jsonString, Class<T> clazz) { if (StringUtils.isEmpty(jsonString)) { return null; } try { return mapper.readValue(jsonString, clazz); } catch (IOException e) { logger.warn("parse json string error:" + jsonString, e); return null; } } /** * 如果对象为Null,返回"null". * 如果集合为空集合,返回"[]". */ public String toJson(Object object) { try { return mapper.writeValueAsString(object); } catch (IOException e) { logger.warn("write to json string error:" + object, e); return null; } } /** * 设置转换日期类型的format pattern,如果不设置默认打印Timestamp毫秒数. */ public void setDateFormat(String pattern) { if (StringUtils.isNotBlank(pattern)) { DateFormat df = new SimpleDateFormat(pattern); mapper.getSerializationConfig().setDateFormat(df); mapper.getDeserializationConfig().setDateFormat(df); } } /** * 取出Mapper做进一步的设置或使用其他序列化API. */ public ObjectMapper getMapper() { return mapper; } }
在其他类中定义jsonBinder对象:
private static JsonBinder binder = JsonBinder.buildNonDefaultBinder();
以下是对象到json字符串以及json字符串到对象的转化:
/**
* 序列化对象/集合到Json字符串.
*/
@Test public void toJson() throws Exception { //Bean TestBean bean = new TestBean("A"); String beanString = binder.toJson(bean); System.out.println("Bean:" + beanString); assertEquals("{\"name\":\"A\"}", beanString); //Map Map<String, Object> map = Maps.newLinkedHashMap(); map.put("name", "A"); map.put("age", 2); String mapString = binder.toJson(map); System.out.println("Map:" + mapString); assertEquals("{\"name\":\"A\",\"age\":2}", mapString); //List<String> List<String> stringList = Lists.newArrayList("A", "B", "C"); String listString = binder.toJson(stringList); System.out.println("String List:" + listString); assertEquals("[\"A\",\"B\",\"C\"]", listString); //List<Bean> List<TestBean> beanList = Lists.newArrayList(new TestBean("A"), new TestBean("B")); String beanListString = binder.toJson(beanList); System.out.println("Bean List:" + beanListString); assertEquals("[{\"name\":\"A\"},{\"name\":\"B\"}]", beanListString); //Bean[] TestBean[] beanArray = new TestBean[] { new TestBean("A"), new TestBean("B") }; String beanArrayString = binder.toJson(beanArray); System.out.println("Array List:" + beanArrayString); assertEquals("[{\"name\":\"A\"},{\"name\":\"B\"}]", beanArrayString); } /** * 从Json字符串反序列化对象/集合. */ @Test @SuppressWarnings("unchecked") public void fromJson() throws Exception { //Bean String beanString = "{\"name\":\"A\"}"; TestBean bean = binder.fromJson(beanString, TestBean.class); System.out.println("Bean:" + bean); //Map String mapString = "{\"name\":\"A\",\"age\":2}"; Map<String, Object> map = binder.fromJson(mapString, HashMap.class); System.out.println("Map:"); for (Entry<String, Object> entry : map.entrySet()) { System.out.println(entry.getKey() + " " + entry.getValue()); } //List<String> String listString = "[\"A\",\"B\",\"C\"]"; List<String> stringList = binder.getMapper().readValue(listString, List.class); System.out.println("String List:"); for (String element : stringList) { System.out.println(element); } //List<Bean> String beanListString = "[{\"name\":\"A\"},{\"name\":\"B\"}]"; List<TestBean> beanList = binder.getMapper().readValue(beanListString, new TypeReference<List<TestBean>>() { }); System.out.println("Bean List:"); for (TestBean element : beanList) { System.out.println(element); } }
在我的实际项目中,遇到一个有意思的问题,我把一个对象转为为json字符串时,调用binder.toJson(bean) ,这个方法,方法总是返回null,后面发现该bean中没有默认的构造函数,加上某人构造函数就ok了
以上部分转载来自于:http://zhangyou1010.iteye.com/blog/1049259
以下是参考人家的,自己写的部分:
/**
* 利用 Jackson 中的 {@link ObjectMapper} 类来让 java 对象和 json 字符串实现互相转换. 在某些场合下将 java 对象转换为 json
* 字符串有很多好处, 比如往缓存中存放数据. 可以看作是对 Jackson 的简单封装, 也可以通过 {@link #getObjectMapper()}
* 方法获得<code>objectMapper</code> 对象来完成其他操作. 为了获得更好的效率, 采用了 singleton 模式, jackson 对此是支持的.
*
* @author
*/
public class JsonBinder { private static ObjectMapper objectMapper = new ObjectMapper(); private static JsonBinder jsonBinder; private JsonBinder(Inclusion inclusion) { // serializing 设置成 Inclusion.NON_DEFAULT 来提高性能 objectMapper.getSerializationConfig().withSerializationInclusion(inclusion); } /** * 允许修改 {@link Inclusion}, 默认是 {@link Inclusion#NON_DEFAULT}, 也即对于未修改的属性不用进行 json 转换. * * @param inclusion * @see #getInstance() */ public static JsonBinder getInstance(Inclusion inclusion) { if (jsonBinder == null) { jsonBinder = new JsonBinder(inclusion); } return jsonBinder; } public static JsonBinder getInstance() { if (jsonBinder == null) { jsonBinder = new JsonBinder(Inclusion.NON_DEFAULT); } return jsonBinder; } /** * 从 json 字符串生成相应的 java 对象. * <ul> * <li>1) 如果 JSON 字符串为 NULL 或 "null", 则返回 null.</li> * <li>2) 如果 JSON 字符串为 "[]", 则返回空集合.</li> * </ul> * * @param <T> * @param jsonString * @param clazz * @return */ public <T> T fromJson(String jsonString, Class<T> clazz) { if (StringUtils.isEmpty(jsonString)) { return null; } try { return objectMapper.readValue(jsonString, clazz); } catch (IOException e) { return null; } } /** * 将 java 对象生成 json 格式. * <ul> * <li>1) 如果对象为 null, 则返回 "null".</li> * <li>2) 如果对象为空集合, 则返回 "[]".</li> * </ul> * * @param object * @return */ public String toJson(Object object) { try { return objectMapper.writeValueAsString(object); } catch (IOException e) { return null; } } /** * 获取 <code>objectMapper</code> 对象, 完成其他该 binder 未封装的功能. * * @return */ public ObjectMapper getObjectMapper() { return objectMapper; } }[/size][/color]