欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Java 序列化

程序员文章站 2022-06-17 09:29:55
...

Serializable 接口

对象实现了 Serializable 接口,就表示可以被序列化,它只是一个标记接口,也叫空接口,没有任何方法,所以实现了接口也不需要实现方法。

转换成 JSON 数据的对象可通过反序列化再次转化成对象JSON.parseObject(info, User.class)

实例Java 序列化

Apartment
import java.io.Serializable;

public class Apartment extends Building implements Serializable {

  private int totalRooms;
  private String builtupArea;

  public int getTotalRooms() {
    return totalRooms;
  }

  public void setTotalRooms(int totalRooms) {
    this.totalRooms = totalRooms;
  }

  public String getBuiltupArea() {
    return builtupArea;
  }

  public void setBuiltupArea(String builtupArea) {
    this.builtupArea = builtupArea;
  }
}
Building
public class Building {
  private String name;
  private String address;

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public String getAddress() {
    return address;
  }

  public void setAddress(String address) {
    this.address = address;
  }
}
ObjectAssembler
public class ObjectAssembler {
  public static void main(String[] args) {
    Apartment apartment = new Apartment();
    apartment.setName("研究生公寓");
    apartment.setAddress("杭州市江干区学林街628号");
    apartment.setTotalRooms(54);
    apartment.setBuiltupArea("380平米");

    String content = JSON.toJSONString(apartment);
    System.out.println("Apartment 对象=" + content);

    Apartment b2 = JSON.parseObject(content, Apartment.class);
    String name = b2.getName();
    System.out.println("Apartment 对象名称=" + name);

    Map bInfo = JSON.parseObject(content, Map.class);
    String name2 = (String) bInfo.get("name");
    System.out.println("Map.name 值=" + name2);
  }
}

排除序列化

解决当前对象部分属性不想被序列化,下面方法任选其一:

  1. 通过在字段上增加一个 @JSONField(serialize=false)注解,这个注解是 fastjson 库提供的。
  2. 在声明字段时,增加一个 transient 修饰关键字,这个关键字是 JDK 本身提供的。
Building
import com.alibaba.fastjson.annotation.JSONField;
import java.io.Serializable;

public class Building implements Serializable {
  // 自定义serialVersionUID
  private static final long serialVersionUID = 8735132092273200831L;

  private transient String name;

  @JSONField(serialize=false)
  private String address;

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public String getAddress() {
    return address;
  }

  public void setAddress(String address) {
    this.address = address;
  }
}