天天看点

什么时候java序列号_java序列化和反序列化

Java 提供了一种对象序列化的机制,一个对象可以表示为一个字节序列,该字节序列包括对象的数据、对象的类型信息和存储在对象中的数据类型。

在将对象序列化之后,可以进行反序列化,即对象的类型信息、对象的数据和对象中的数据类型可以用来在内存中新建对象。整个过程是JVM独立的。(参考:http://www.runoob.com/java/java-serialization.html)

使用Jackson方式

1、类 ExamineResult.java:

package com.capinfo.jrjvcpe.modules.record.entity;

public class ExamineResult {

Integer result; //审核结果:0 未通过 1 通过

String opinion; //审批意见

public ExamineResult() {

super();

}

public ExamineResult(Integer result, String opinion) {

this.result = result;

this.opinion = opinion;

}

//setter and getter ...

}

1、以 Map 为例进行序列化和反序列化的操作:

Map result = new HashMap<>();

ExamineResult a = new ExamineResult("1", "审核意见a");

ExamineResult b = new ExamineResult("0", "审核意见b");

ExamineResult c = new ExamineResult("1", "审核意见c");

result.put("a", a);

result.put("b", b);

result.put("c", c);

//序列化

ObjectMapper mapper = new ObjectMapper(); //转换器

try {

String json = mapper.writeValueAsString(result);

//将对象转换为json格式的字符串

} catch (JsonProcessingException e) {

e.printStackTrace();

}

//反序列化

//Map m = (Map) mapper.readValue(json, Map.class);

//可以改为:

Map m = mapper.readValue(json, new TypeReference>() {});

System.out.println(m.get("a").getOpinion());

System.out.println(m.get("b").getOpinion());

System.out.println(m.get("c").getOpinion());