赞
踩
<!--添加fastjson依赖-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.7</version>
</dependency>
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.tl.entity.User; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class FastJson { /** * 将String类型转换为json字符串 * * @param object * @return */ public static Object strJson(String object) { Object o = JSON.toJSONString(object); return o; } /** * 将List 集合转换成json字符串 * * @param list * @return */ public static Object listJson(List list) { String listJson = JSON.toJSONString(list); return listJson; } /** * 将map 转换成json * * @param map * @return */ public static Object mapJson(Map map) { String mapJson = JSON.toJSONString(map); return mapJson; } /** * 将josn字符串转成list<T>集合 * * @param list * @param tClass pojo对象 * @param <T> * @return */ public static <T> List<T> strListToList(String list, Class<T> tClass) { List<T> strListToList = (List<T>) JSONArray.parseArray(list, tClass); return strListToList; } /** * 将json字符串转换为map * * @param strMap 序列化的map * @return */ public static Map strMapToMap(String strMap) { Map map = JSONObject.parseObject(strMap, Map.class); return map; } }
public class User { private String id; private String name; private String password; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
public static void main(String[] args) { //序列化String System.out.println(FastJson.strJson("123")); //将list集合序列化 List<User> userList = new ArrayList<>(); User u1 = new User(); u1.setId("123"); u1.setName("123"); u1.setPassword("123"); User u2 = new User(); u2.setId("456"); u2.setName("456"); u2.setPassword("456"); userList.add(u1); userList.add(u2); System.out.println(FastJson.listJson(userList)); //将map序列化 Map map = new HashMap(); map.put("key1", "123"); map.put("key2", "123"); System.out.println(FastJson.mapJson(map)); //将序列化的list集合反序列化 List<User> userlist = FastJson.strListToList("[{\"id\":\"123\",\"name\":\"123\",\"password\":\"123\"},{\"id\":\"456\",\"name\":\"456\",\"password\":\"456\"}]", User.class); for (User x : userList) { System.out.println("姓名:" + x.getName()); } //将序列化的map反序列化 Map strMapToMap = FastJson.strMapToMap("{\"key1\":\"123\",\"key2\":\"123\"}"); for (Object key : strMapToMap.keySet()) { System.out.println("key:" + key + ",值" + strMapToMap.get(key)); } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。