添加依赖
<dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.7</version></dependency>
List,实体类字符串想换转换
package Map;import com.alibaba.fastjson.*;
import dto.Person;import java.util.ArrayList;
import java.util.List;public class JsonUtils {public static void main(String[] args) {List<Person> list = new ArrayList<Person>();Person person1 = new Person();person1.setName("张三");person1.setAge(18);list.add(person1);Map<String, String> map = new HashMap<>();map.put("张三", "男");map.put("李四", "男");map.put("王五", "女");//实体类转StringString str = JSON.toJSONString(person1);//list转为StringString strList = JSON.toJSONString(list);String str2 = JSONObject.toJSONString(list);String str3 = JSONArray.toJSONString(list);// map转StringString mapStr = JSON.toJSONString(map);//String转实体类Person person = JSON.parseObject(str, Person.class);//String转Json对象JSONObject jsonObject = JSONObject.parseObject(str);//String转为listList<Person> list1 = JSON.parseArray(strList, Person.class);List<Person> list2 = JSONObject.parseArray(str, Person.class);List<Person> list3 = JSONArray.parseArray(str, Person.class);//String转JsonArray对象JSONArray jsonArray = JSONArray.parseArray(strList);//String转mapMap<String, String> map1 = JSON.parseObject(mapStr,Map.class);}}
List,Map相互转换(java8 stream流)
List转Map
/*** List -> Map* toMap 如果集合对象有重复的key,会报错Duplicate key ....* 可以用 (k1,k2)->k1 来设置,如果有重复的key,则保留key1,舍弃key2*/Map<String, Person> appleMap = list1.stream().collect(Collectors.toMap(Person::getName, a -> a, (k1, k2) -> k1));
Map转List
/**
* Map -> List
*/
List<Integer> result1 = map.keySet().stream().collect(Collectors.toList());
List<String> result2 = map.values().stream().collect(Collectors.toList());