首页 > 代码库 > java对象与字符串的序列化和反序列化
java对象与字符串的序列化和反序列化
import java.io.ByteArrayInputStream;import java.io.ByteArrayOutputStream;import java.io.ObjectInputStream;import java.io.ObjectOutputStream;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;import org.slf4j.Logger;import org.slf4j.LoggerFactory;public class SerializeUtils { private static final Logger LOG = LoggerFactory.getLogger(SerializeUtils.class); /** * 对象序列化为字符串 */ public static String serialize(Object obj) throws Exception { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream); objectOutputStream.writeObject(obj); String serStr = byteArrayOutputStream.toString("ISO-8859-1");//必须是ISO-8859-1 serStr = java.net.URLEncoder.encode(serStr, "UTF-8");//编码后字符串不是乱码(不编也不影响功能) LOG.info("对象obj:【" + obj + "】序列化serStr:【" + serStr + "】"); objectOutputStream.close(); byteArrayOutputStream.close(); return serStr; } /** * 字符串 反序列化为 对象 */ public static Object unSerialize(String serStr) throws Exception { String redStr = java.net.URLDecoder.decode(serStr, "UTF-8"); ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(redStr.getBytes("ISO-8859-1")); ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream); Object obj = objectInputStream.readObject(); LOG.info("对象obj:【" + obj + "】反序列化serStr:【" + serStr + "】"); objectInputStream.close(); byteArrayInputStream.close(); return obj; } public static void main(String[] args) throws Exception { List<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>(); HashMap<String, String> map = new HashMap<String, String>(); map.put("number", "123"); map.put("name", "test"); list.add(map); HashMap<String, String> map2 = new HashMap<String, String>(); map2.put("number", "1232"); map2.put("name", "test2"); list.add(map2); String str=serialize(list); System.err.println(str); List<HashMap<String, String>> newList=(List<HashMap<String, String>>) unSerialize(str); for(Map m : newList) { System.out.println(m.get("number") + " " + m.get("name")); } }
java对象与字符串的序列化和反序列化
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。