利用jackson中的objectmapper对象,转为对象为json字符串,springside对jackson的简单封装 jsonbinder :
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了。