java中用ObjectMapper类实现Json与bean的转换示例

时间:2021-05-19

前言

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()); } }}

或者

@Controllerpublic 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); }

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对的支持。

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章