Java对象 转 JSON字符串
JAR包
<dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.47</version> </dependency>
USER类
package com.example.demo.entity; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; //需要导入lombok @Data @AllArgsConstructor @NoArgsConstructor public class User { private String name; private int age; private String sex; }
package com.kuang.controller; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.kuang.pojo.User; import java.util.ArrayList; import java.util.List; public class FastJsonDemo { public static void main(String[] args) { //创建一个对象 User user1 = new User("秦疆1号", 3, "男"); User user2 = new User("秦疆2号", 3, "男"); User user3 = new User("秦疆3号", 3, "男"); User user4 = new User("秦疆4号", 3, "男"); List<User> list = new ArrayList<User>(); list.add(user1); list.add(user2); list.add(user3); list.add(user4); System.out.println("*******Java对象 转 JSON字符串*******"); String str1 = JSON.toJSONString(list); System.out.println("JSON.toJSONString(list)==>"+str1); String str2 = JSON.toJSONString(user1); System.out.println("JSON.toJSONString(user1)==>"+str2); System.out.println("\n****** JSON字符串 转 Java对象*******"); User jp_user1=JSON.parseObject(str2,User.class); System.out.println("JSON.parseObject(str2,User.class)==>"+jp_user1); System.out.println("\n****** Java对象 转 JSON对象 ******"); JSONObject jsonObject1 = (JSONObject) JSON.toJSON(user2); System.out.println("(JSONObject) JSON.toJSON(user2)==>"+jsonObject1.getString("name")); System.out.println("\n****** JSON对象 转 Java对象 ******"); User to_java_user = JSON.toJavaObject(jsonObject1, User.class); System.out.println("JSON.toJavaObject(jsonObject1, User.class)==>"+to_java_user); } }
输出为:
*******Java对象 转 JSON字符串******* JSON.toJSONString(list)==>[{"age":3,"name":"秦疆1号","sex":"男"},{"age":3,"name":"秦疆2号","sex":"男"},{"age":3,"name":"秦疆3号","sex":"男"},{"age":3,"name":"秦疆4号","sex":"男"}] JSON.toJSONString(user1)==>{"age":3,"name":"秦疆1号","sex":"男"} ****** JSON字符串 转 Java对象******* JSON.parseObject(str2,User.class)==>User(name=秦疆1号, age=3, sex=男) ****** Java对象 转 JSON对象 ****** (JSONObject) JSON.toJSON(user2)==>秦疆2号 ****** JSON对象 转 Java对象 ****** JSON.toJavaObject(jsonObject1, User.class)==>User(name=秦疆2号, age=3, sex=男)
JAVA对象转MAP
jar
<dependency> <groupId>commons-beanutils</groupId> <artifactId>commons-beanutils</artifactId> <version>1.9.3</version> </dependency>
package com.example.demo.controller.Demo; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.example.demo.entity.User; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class demoTest3 { public static void main(String[] args) throws IllegalAccessException { //创建一个对象 //JAVA中将对象转为Map类型 User user = new User(); user.setName("闫文超"); user.setSex("男"); user.setAge(16); Map map1 = beanToMap(user); System.out.println("\n****** Java对象 转Map*******"); System.out.println("Map" + map1); Map<String, Object> map2 = objectToMap2(user); System.out.println("\n****** Java对象 转Map*******"); System.out.println("JSON.parseObject(JSON.toJSONString(obj), Map.class)==>" + map2); } /** * 将java对象转换为Map * @param obj * @return */ public static Map<String, Object> objectToMap2(Object obj) { return JSON.parseObject(JSON.toJSONString(obj), Map.class); } /** * 将java对象转换为Map * @param object * @return * @throws IllegalAccessException */ public static Map beanToMap(Object object) throws IllegalAccessException { Map<String, Object> map = new HashMap<String, Object>(); Field[] fields = object.getClass().getDeclaredFields(); for (Field field : fields) { field.setAccessible(true); map.put(field.getName(), field.get(object)); } return map; } }
Map转java对象
package com.example.demo.controller.Demo; import com.example.demo.entity.User; import org.apache.commons.beanutils.BeanUtils; import java.beans.BeanInfo; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; public class demoTest3 { public static void main(String[] args) throws IllegalAccessException { User user = new User(); Map<String, Object> map = new HashMap<String, Object>(); map.put("name", "闫文超"); map.put("sex", "男"); map.put("age", 16); // 将map转换为java对象(bean) Object user1 = transMap2Bean(map, user); System.out.println("\n****** Map转Java对象******"); System.out.println("工具demo1"+user1); Object user2 = transMapBean(map, user); System.out.println("\n****** Map转Java对象******"); System.out.println("工具demo2"+user2); } /** * 将map转换为java对象(bean) * * @param map * @param obj * @return */ public static User transMap2Bean(Map<String, Object> map, Object obj) { if (map == null || obj == null) { return null; } try { BeanUtils.populate(obj, map); } catch (Exception e) { e.printStackTrace(); } return (User) obj; } public static User transMapBean(Map<String, Object> map, Object obj) { try { BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass()); PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); for (PropertyDescriptor property : propertyDescriptors) { String key = property.getName(); if (map.containsKey(key)) { Object value = map.get(key); // 得到property对应的setter方法 Method setter = property.getWriteMethod(); setter.invoke(obj, value); } } } catch (Exception e) { e.printStackTrace(); } return (User) obj; } }
List转map
package com.example.面向对象1; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.stream.Collectors; public class listdemo { public static void main(String[] args) { List<String> list = new ArrayList<>(); list.add("aaa"); list.add("bbb"); list.add("ccc"); Map<String, String> map = list.stream().collect(Collectors.toMap(key -> key, value -> value)); System.out.println(map); } }
List和Map 的相互转换
package com.example.面向对象1; import java.util.*; import java.util.stream.Collectors; public class listdemo { public static void main(String[] args) { List<String> list = new ArrayList<>(); list.add("aaa"); list.add("bbb"); list.add("ccc"); //java的 Map<String, String> map1 = list.stream().collect(Collectors.toMap(key -> key, value -> value)); System.out.println("\n********list对象 转 map*******"); System.out.println("stream=1=>" + map1); List<user> list6 = new ArrayList<>(); list6.add(new user(1, "a")); list6.add(new user(2, "b")); list6.add(new user(3, "c")); // 遍历 Map<Integer, String> keyValueMap = new HashMap<>(); for (user keyValue : list6) { keyValueMap.put(keyValue.getId(), keyValue.getName()); } keyValueMap.forEach((k, v) -> System.out.println(k + " ==> " + v)); // Java8 Stream Map<Integer, String> ma1p1 = list6.stream().collect(Collectors.toMap(user::getId, user::getName)); System.out.println("\n********list对象 转 map*******"); System.out.println("stream=2=>" + ma1p1); //todo----------------------------------------------------------------------------------------- //map转list Map<Integer, String> map = new HashMap<>(); map.put(10, "apple"); map.put(20, "orange"); map.put(30, "banana"); map.put(40, "watermelon"); map.put(50, "dragonfruit"); System.out.println("\n******** map转 list 获取key值 *******"); List<Integer> result = new ArrayList(map.keySet()); result.forEach(System.out::println); System.out.println("\n******** map转 list 获取value值 *******"); List<String> result2 = new ArrayList(map.values()); result2.forEach(System.out::println); Map map2 = new HashMap(); map2.put("yan", "xi"); map2.put("wen", "huan"); map2.put("chao", "ni"); List list1 = new ArrayList(map2.keySet()); List list2 = new ArrayList(map2.values()); System.out.println("\n******** map转 list 获取key值 *******"); System.out.println("map转list获取key的值==>"+list1); System.out.println("\n******** map转 list 获取value值 *******"); System.out.println("map转list获取value的值==>"+ list2); } // public Map<String, List<Student>> groupList(List<Student> students) { // Map<String, List<Student>> map = students.stream().collect(Collectors.groupingBy(Student::getName)); // return map; // } }