如何在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); }
关于如何在java项目中利用ObjectMapper类将Json与bean进行转换问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注亿速云行业资讯频道了解更多相关知识。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。