筆者在使用SSM框架項目部分功能進行測試需要使用到對象的序列化與反序列化
第一種方式:jackson
Demo
package com.dznfit.service; import com.dznfit.controller.LoginController; import com.dznfit.entity.User; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import javaConfiguration.RootConfig; import javaConfiguration.WebConfig; import org.apache.log4j.Logger; import org.junit.Test; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import the_mass.redis.SerializeUtil; import java.io.IOException; import java.util.ArrayList; public class UserServiceImplTest { private static Logger logger = Logger.getLogger(UserServiceImplTest.class); @Test public void login() throws IOException { User user = new User(1, "dz", "123", 1); //放入容器 AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(RootConfig.class); //得到bean UserServiceImpl bean = context.getBean(UserServiceImpl.class); /** * ObjectMapper是JSON操作的核心,Jackson的所有JSON操作都是在ObjectMapper中實現。 */ ObjectMapper mapper = new ObjectMapper(); System.out.println("類名" + bean.login((user)).getClass().getName()); String s = mapper.writeValueAsString(bean.login(user)); System.out.println("序列化:" + s); System.out.println("反序列化:" + mapper.readValue(s, User.class)); } }
結果:
我們可以看到jackson實現類
ObjectMapper有許多方法
序列化時給個Object對象就可以了轉成json字符串
反序列化也是有很多
第二種使用java自帶序列化
需要在實體類實現 implements Serializable接口
@Test public void Serialization() throws IOException, ClassNotFoundException { Jedis jedis = new Jedis(); //java原生序列化 ByteArrayOutputStream stream = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(stream); oos.writeObject(new News(1, "sdj", "merry christmas")); oos.writeObject(new News(2, "zdm", "mashangyaoofangjiale")); jedis.set("news-01".getBytes(), stream.toByteArray()); oos.close(); System.out.println("---------"); System.out.println(jedis.get("news-01").getBytes().length); System.out.println(jedis.get("news-01".getBytes()).length); //反序列化 //這里有一個坑在調用jedis.get("news-01").getBytes() --error // 這樣調用的話會改變字節碼取的時候就不對了 //存jedis.set("news-01".getBytes())取所有也是jedis.get("news-01".getBytes()); ByteArrayInputStream bri = new ByteArrayInputStream(jedis.get("news-01".getBytes())); ObjectInputStream outs = new ObjectInputStream(bri); Object o = outs.readObject(); Object o1 = outs.readObject(); System.out.println(o); System.out.println(o1); outs.close(); }
結果