前言
ObjectMapper是jackson中的方法,本文主要给大家介绍了关于java中用ObjectMapper类实现Json与bean转换的相关内容,分享出来供大家参考学习,下面话不多说了,来一起看看详细的介绍吧。
一、将json字符串转为bean
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
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()); } } } |
或者
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
@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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
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); } |
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对服务器之家的支持。
原文链接:http://blog.csdn.net/cc_yy_zh/article/details/77185130