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

总结

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

声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:notice#nhooo.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。