java中用ObjectMapper类实现Json与bean的转换示例
程序员文章站
2024-02-24 11:12:22
前言
objectmapper是jackson中的方法,本文主要给大家介绍了关于java中用objectmapper类实现json与bean转换的相关内容,分享出来供大家...
前言
objectmapper是jackson中的方法,本文主要给大家介绍了关于java中用objectmapper类实现json与bean转换的相关内容,分享出来供大家参考学习,下面话不多说了,来一起看看详细的介绍吧。
一、将json字符串转为bean
public class jsontojavabean { public static void main(string[] args) { string str="{\"student\":[{\"name\":\"leilei\",\"age\":23},{\"name\":\"leilei02\",\"age\":23}]}"; student stu = null; list list = null; try { objectmapper objectmapper=new objectmapper(); studentlist studentlist=objectmapper.readvalue(str,studentlist.class); list=studentlist.getstudent(); } catch (exception e) { // todo auto-generated catch block e.printstacktrace(); } for(student s:list){ system.out.println(s.getname()+" "+s.getage()); } } }
或者
@controller public class ordercontroller extends basecontroller { @autowired private objectmapper objectmapper1; @requestmapping(value = "/order/searchorderimportbyitem") public responsedata searchorderimportbyitem(@requestparam("page") integer page, @requestparam("pagesize") integer pagesize, httpservletrequest request) { try { string formdata = request.getparameter("formdata"); orderqueryrequest orderqueryrequest = null; if (stringutils.isnotblank(formdata)) { objectmapper1.setdateformat(new simpledateformat("yyyy-mm-dd hh:mm")); orderqueryrequest = objectmapper1.readvalue(formdata, orderqueryrequest.class); } else { return null; } pagehelper.startpage(page, pagesize); list<orderqueryrequest> list = orderservice.searchorderimportbyitem(orderqueryrequest); return new responsedata(list); } catch (exception e) { e.printstacktrace(); } return null; } }
二、将bean转为json
public static void main(string[] args) { arraylist list=new arraylist(); student s1=new student(); s1.setname("leilei"); s1.setage(23); student s2=new student(); s2.setname("leilei02"); s2.setage(23); list.add(s1); list.add(s2); stringwriter str=new stringwriter(); objectmapper objectmapper=new objectmapper(); try { objectmapper.writevalue(str, list); } catch (exception e) { // todo auto-generated catch block e.printstacktrace(); } system.out.println(str); }
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对的支持。
下一篇: 使用JSP开发WebMail系统