首页 > 开发 > Java > 正文

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

2024-07-13 10:11:14
字体:
来源:转载
供稿:网友

前言

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

总结

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


注:相关教程知识阅读请移步到JAVA教程频道。
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表