String字符串转List<JavaBean>

使用的是fastjson

//json数组字符串转List<JavaBean>
String str = "[{\"journeyDate\":\"2021-07-01\",\"journeyWay\":\"1\",\"travelToolNo\":\"122\",\"goPlace\":\"北京\",\"toPlace\":\"惠州\"},{\"journeyDate\":\"2021-07-04\",\"journeyWay\":\"1\",\"travelToolNo\":\"123\",\"goPlace\":\"惠州\",\"toPlace\":\"北京\"}]"; List<SojournHistory> arr = (List<SojournHistory>) JSON.parseObject(str,new TypeReference<ArrayList<SojournHistory>>() {}); System.out.println(arr.get(0).getToPlace());

 

这里再扩展一下fastjson涉及到的常用方法

//json字符串转json对象
String str = "{\"name\":\"aa\",\"high\":172}"; JSONObject jsonObject = JSON.parseObject(str); JSONObject jsonObject1 = JSONObject.parseObject(str);
System.out.println(jsonObject.getString("name")+":"+jsonObject.getInteger("high"));
//json数组字符串转JsonArray
String str = "[{\"name\":\"aa\",\"high\":172},{\"name\":\"bb\",\"high\":175}]"; JSONArray ja = JSON.parseArray(str); JSONArray js = JSONArray.parseArray(str); System.out.println(ja.getJSONObject(0).getString("name"));
//json字符串转JavaBean
String str = "{\"name\":\"aa\",\"high\":172}"; Student student = JSON.parseObject(str, new TypeReference<Student>() {}); Student student1 = JSONObject.parseObject(str, new TypeReference<Student>() {}); System.out.println(student.getName()+":"+student.getHigh());
//json字符串转List<JavaBean>
String str = "[{\"name\":\"aa\",\"high\":172},{\"name\":\"bb\",\"high\":175}]"; List<Student> arr = (List<Student>) JSON.parseObject(str,new TypeReference<ArrayList<Student>>() {}); List<Student> arrs = JSONArray.parseObject(str, new TypeReference<ArrayList<Student>>() {}); System.out.println(arr.get(0).getName());
//JavaBean转Map
Map<String, Object> a = (Map<String, Object>)JSON.toJSON(javabean);
//JavaBean转Map
Map<String, Object> a = JSON.parseObject(JSON.toJSONString(javabean));
//JavaBean 转 Map 时,Date类型字段格式化
JSON.DEFFAULT_DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";
Map<String, Object> map = (Map<String, Object>) JSON.parseObject(JSON.toJSONString(plan, SerializerFeature.WriteDateUseDateFormat));

 

//dto 转 map
Map<String,Object> map = JSON.parseObject(JSON.toJSONString(dto));

 

 FastJson官网:戳这里

 

posted @ 2021-07-19 10:07  ジ绯色月下ぎ  阅读(1263)  评论(0编辑  收藏  举报