您好,登錄后才能下訂單哦!
如何在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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。