java序列化与反系列化,serializable原理,Parcelable接口原理解析,Json,XML

Java的序列化和反序列化是用于对象的持久化和传输的重要机制。以下是对相关概念的详细解释:

Java 序列化与反序列化

序列化 (Serialization) 是将 Java 对象转换为字节流的过程,这样对象就可以通过网络传输或者保存到文件中。反序列化 (Deserialization) 是将字节流重新转换为 Java 对象的过程。

序列化的步骤
  1. 实现 Serializable 接口。
  2. 使用 ObjectOutputStream 将对象写入到输出流中。
java 复制代码
import java.io.Serializable;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.io.IOException;

public class Person implements Serializable {
    private static final long serialVersionUID = 1L;
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public static void main(String[] args) {
        Person person = new Person("John", 30);
        try (FileOutputStream fileOut = new FileOutputStream("person.ser");
             ObjectOutputStream out = new ObjectOutputStream(fileOut)) {
            out.writeObject(person);
        } catch (IOException i) {
            i.printStackTrace();
        }
    }
}
反序列化的步骤
  1. 使用 ObjectInputStream 从输入流中读取对象。
java 复制代码
import java.io.FileInputStream;
import java.io.ObjectInputStream;
import java.io.IOException;

public class DeserializePerson {
    public static void main(String[] args) {
        Person person = null;
        try (FileInputStream fileIn = new FileInputStream("person.ser");
             ObjectInputStream in = new ObjectInputStream(fileIn)) {
            person = (Person) in.readObject();
        } catch (IOException i) {
            i.printStackTrace();
        } catch (ClassNotFoundException c) {
            System.out.println("Person class not found");
            c.printStackTrace();
        }
        System.out.println("Deserialized Person...");
        System.out.println("Name: " + person.name);
        System.out.println("Age: " + person.age);
    }
}

Serializable 原理

Serializable 是一个标记接口(没有任何方法),它向 JVM 指示该类的对象可以被序列化。序列化过程中,JVM 将该对象的状态保存为字节流,包括其所有非瞬态和非静态字段。

Parcelable 接口原理解析

Parcelable 是 Android 特有的接口,用于更高效地在不同的进程之间传输对象。相比于 SerializableParcelable 更适合 Android,因为它在内存开销和性能上更为高效。

实现 Parcelable 接口的步骤
  1. 实现 Parcelable 接口。
  2. 实现 writeToParcel 方法,将对象的字段写入 Parcel
  3. 实现 CREATOR 静态字段,负责反序列化 Parcelable 对象。
java 复制代码
import android.os.Parcel;
import android.os.Parcelable;

public class Person implements Parcelable {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    protected Person(Parcel in) {
        name = in.readString();
        age = in.readInt();
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(name);
        dest.writeInt(age);
    }

    @Override
    public int describeContents() {
        return 0;
    }

    public static final Creator<Person> CREATOR = new Creator<Person>() {
        @Override
        public Person createFromParcel(Parcel in) {
            return new Person(in);
        }

        @Override
        public Person[] newArray(int size) {
            return new Person[size];
        }
    };
}

JSON (JavaScript Object Notation)

JSON 是一种轻量级的数据交换格式,易于人类阅读和编写,同时也易于机器解析和生成。Java 中可以使用库如 GsonJackson 来处理 JSON 数据。

使用 Gson 进行 JSON 序列化和反序列化
java 复制代码
import com.google.gson.Gson;

public class JsonExample {
    public static void main(String[] args) {
        Gson gson = new Gson();
        Person person = new Person("John", 30);

        // 序列化
        String json = gson.toJson(person);
        System.out.println(json);

        // 反序列化
        Person person2 = gson.fromJson(json, Person.class);
        System.out.println("Name: " + person2.name);
        System.out.println("Age: " + person2.age);
    }
}

XML (Extensible Markup Language)

XML 是一种标记语言,用于描述数据。Java 中可以使用 JAXB (Java Architecture for XML Binding) 或 XStream 等库来处理 XML 数据。

使用 JAXB 进行 XML 序列化和反序列化
java 复制代码
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import java.io.StringReader;
import java.io.StringWriter;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Person {
    private String name;
    private int age;

    // Default constructor is required for JAXB
    public Person() {}

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @XmlElement
    public String getName() {
        return name;
    }

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

    @XmlElement
    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public static void main(String[] args) throws JAXBException {
        Person person = new Person("John", 30);

        // 序列化
        JAXBContext context = JAXBContext.newInstance(Person.class);
        Marshaller marshaller = context.createMarshaller();
        StringWriter writer = new StringWriter();
        marshaller.marshal(person, writer);
        String xml = writer.toString();
        System.out.println(xml);

        // 反序列化
        Unmarshaller unmarshaller = context.createUnmarshaller();
        Person person2 = (Person) unmarshaller.unmarshal(new StringReader(xml));
        System.out.println("Name: " + person2.getName());
        System.out.println("Age: " + person2.getAge());
    }
}

这就是 Java 中序列化与反序列化、Serializable 原理、Parcelable 接口原理以及 JSON 和 XML 的解析方法。

相关推荐
爱编程的小新☆10 小时前
【LeetCode】从递归到 Flood Fill:5 道题吃透 DFS 的选择、回溯与标记
java·算法·leetcode·深度优先·回溯·flood fill
weixin_3831964710 小时前
java基础面试题@Autowired和@Resource区别
java·开发语言
evans在进步10 小时前
LeetCode 33:搜索旋转排序数组——Java 两阶段二分查找详解
java·python·leetcode
Web Security Loop11 小时前
MAC卸载JDK环境
java·macos·jdk
Rain的Java大神之路12 小时前
线上接口负载满了如何解决
java·数据库·redis·后端·缓存·面试·架构
counting money12 小时前
Tomcat 专题:从基础架构到性能调优与 WebSocket 实战
java·websocket·tomcat
xiaohaiAIgeo13 小时前
【2026年】HG/T 20656-2024化工暖通空调设计规范:新版标准的变化与影响
java·前端·javascript·科普知识
小强库计算机毕业设计13 小时前
基于 Spring Boot + Vue3 的校园管理系统
java·spring boot·后端·项目实战·管理系统·技术分享·校园管理系统实战
霸道流氓气质13 小时前
Java中信号量(Semaphore):从本地到分布式
java·开发语言·分布式
怪奇云呼军13 小时前
G.711、Opus 和重采样会拖慢识别吗?闪电智能VoiceAgent 的音频入口怎么选
java·人工智能·python·算法·云计算·音视频