java将类序列化为字符串,和将字符串反序列化类。未涉及到序列化字符串的加密,如果考虑安全,需要使用加密算法。
可以考虑用google json序列化。
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
/**
* Created by fashici on 17-6-15.
*/
public class Experiment implements Serializable {
protected final static Logger LOGGER = LoggerFactory.getLogger(Experiment.class);
private final static long serialVersionUID = 1;
private final static String CHARSET_NAME = "ISO-8859-1";
/**
* @brief 字符串反序列化为类
* @param serializedString
* @return
*/
public static Experiment deserialized(String serializedString){
try {
ByteArrayInputStream bis = new ByteArrayInputStream(
serializedString.getBytes(CHARSET_NAME));
ObjectInputStream ois = new ObjectInputStream(bis);
Experiment experiment = (Experiment) ois.readObject();
ois.close();
return experiment;
} catch (Exception e) {
LOGGER.info("deserialized error! serializedString is {}.", serializedString, e);
Experiment experiment = new Experiment();
return experiment;
}
}
/**
* @brief 类序列化为字符串
* @return
*/
public String serialized() {
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(this);
oos.flush();
String serializedString = baos.toString(CHARSET_NAME);
baos.close();
oos.close();
return serializedString;
} catch (Exception e) {
LOGGER.info("serialized error!", e);
return "";
}
}
}参考:
https://stackoverflow.com/questions/13568248/how-to-binary-deserialize-object-into-form-string