package com.wing.mall.cloud.base.test.json; import com.alibaba.druid.support.json.JSONUtils; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import lombok.Data; import java.util.*; @Data public class Person { //@JSONField(name = "AGE") private int age; //@JSONField(name = "FULL NAME") private String fullName; //@JSONField(name = "DATE OF BIRTH") private Date dateOfBirth; public Person(int age, String fullName, Date dateOfBirth) { super(); this.age = age; this.fullName= fullName; this.dateOfBirth = dateOfBirth; } public static void main(String[] args) { Person zhangsan = new Person(18, "zhangsan", new Date()); //1:对象转JSON字符串 String string = JSON.toJSONString(zhangsan); System.out.println(string); /**输出: * {"age":18,"dateOfBirth":1591749219656,"fullName":"zhangsan"} */ //------------------------------------- //2:JSON字符串转对象 Person person = JSON.parseObject(string,Person.class); System.out.println(person); /** * 输出: * Person(age=18, fullName=zhangsan, dateOfBirth=Wed Jun 10 08:47:12 GMT+08:00 2020) */ //-------------------------------------- //3:list对象转JSON字符串 List<Person> listOfPersons = new ArrayList<Person>(); listOfPersons.add(new Person(19, "lisi", new Date())); listOfPersons.add(new Person(20, "wanger", new Date())); String string1 = JSON.toJSONString(listOfPersons); System.out.println(string1); /** * 输出: * [{"age":19,"dateOfBirth":1591749437754,"fullName":"lisi"},{"age":20,"dateOfBirth":1591749437754,"fullName":"wanger"}] */ //---------------------------------------- //4: list的字符串转List集合。 List<Person> ts = (List<Person>) JSONArray.parseArray(string1, Person.class); ts.forEach(person1 -> { System.out.println(person1); }); /** * 输出: * Person(age=19, fullName=lisi, dateOfBirth=Wed Jun 10 09:19:14 GMT+08:00 2020) * Person(age=20, fullName=wanger, dateOfBirth=Wed Jun 10 09:19:14 GMT+08:00 2020) */ //------------------------------------------------- //5:Map转JSON字符串 Map<String, Object> map = new HashMap<>(); map.put("a", "aaa"); map.put("b", "bbb"); map.put("c", 1); String string2 = JSONUtils.toJSONString(map); System.out.println(string2); /** * 输出: * {"a":"aaa","b":"bbb","c":1} */ //--------------- //6:JSON字符串转Map Map<String, Object> maps = (Map<String, Object>) JSON.parse(string2); maps.forEach((k,v)->{ System.out.println("k:" + k + " " + "v:" + v); }); /** * 输出: * k:a v:aaa * k:b v:bbb * k:c v:1 */ } }