Java序列化和JSON字符串都是Java中用于數(shù)據(jù)傳輸和存儲的方式,下面分別介紹一下。
Java序列化
Java序列化是Java中用于將對象轉(zhuǎn)換為字節(jié)序列的過程,方便在網(wǎng)絡(luò)或本地文件中進(jìn)行存儲和傳輸。Java序列化需要實(shí)現(xiàn)Serializable接口,并使用ObjectInputStream和ObjectOutputStream進(jìn)行讀寫。
public class Person implements Serializable { private String name; private int age; // getters and setters @Override public String toString() { return "Person{" + "name='" + name + '\'' + ", age='" + age + '\'' + '}'; } } public static void main(String[] args) { Person person = new Person("Jack", 25); try { FileOutputStream fileOut = new FileOutputStream("/tmp/person.ser"); ObjectOutputStream out = new ObjectOutputStream(fileOut); out.writeObject(person); out.close(); fileOut.close(); } catch (IOException e) { e.printStackTrace(); } Person deserializedPerson = null; try { FileInputStream fileIn = new FileInputStream("/tmp/person.ser"); ObjectInputStream in = new ObjectInputStream(fileIn); deserializedPerson = (Person) in.readObject(); in.close(); fileIn.close(); } catch (IOException | ClassNotFoundException e) { e.printStackTrace(); } System.out.println(deserializedPerson); // Person{name='Jack', age='25'} }
JSON字符串
JSON是一種輕量級的數(shù)據(jù)交換格式,常用于網(wǎng)絡(luò)傳輸和存儲。Java中可以使用第三方庫如Jackson或Gson進(jìn)行JSON字符串的序列化和反序列化。
public class Person { private String name; private int age; // getters and setters @Override public String toString() { return "Person{" + "name='" + name + '\'' + ", age='" + age + '\'' + '}'; } } public static void main(String[] args) { ObjectMapper objectMapper = new ObjectMapper(); Person person = new Person("Jack", 25); try { FileWriter fileWriter = new FileWriter("/tmp/person.json"); objectMapper.writeValue(fileWriter, person); fileWriter.close(); } catch (IOException e) { e.printStackTrace(); } String json = "{\"name\":\"Jack\",\"age\":25}"; try { Person deserializedPerson = objectMapper.readValue(json, Person.class); System.out.println(deserializedPerson); // Person{name='Jack', age='25'} } catch (JsonProcessingException e) { e.printStackTrace(); } }