java用ObjectMapper实现Json与bean转换 java中用ObjectMapper类实现Json与bean的转换示例
cc_yy_zh 人气:0想了解java中用ObjectMapper类实现Json与bean的转换示例的相关内容吗,cc_yy_zh在本文为您仔细讲解java用ObjectMapper实现Json与bean转换的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:objectmapper转json,javabean转换成json,将javabean,转换json,下面大家一起来学习吧。
前言
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); }
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对的支持。
加载全部内容