Write only object java

Write only object java

Object flow

Object Serialization
ObjectOutputStream -> Serialization -> Write objects, will be «second
Writing / byte «is written (file)
ObjectInputStream -> Anti-serialization -> Read object

Convert JAVA objects into byte sequences (IO byte stream)

Object Deserialization
Restore Java objects from byte sequences

Why is serialized
The object after serialization can be saved on the disk or transmit it on the network.
Make different computers to share objects. Serialized byte sequence is flat
Desk irrelevant )

Object serialization conditions
Only realizedSerializable The object of the interface of the interface can be serialized.
There is no way in the serializable interface, and the class that implements the interface does not need
Implement additional methods.
If the properties of the object are objects, the attribute corresponding class must also implement serializable
interface

How to realize serialization
Create ObjectOutputStream objects
Call WRITEOBJECT () Output Output

How to achieve reverse sequence
Create ObjectInputStream objects
Call readObject () read object

Write a small example

Because it is an object stream, it is sure to use the object, write to create a Person class, including the name, age attribute, and achieve GET () set () toString () has a parameter and no parametric method, The most important thing is the Person class to implement the serializable interface

 1 import java.io.Serializable; 2 3 public class Person implements Serializable //Have a capability, serialization and reverse sequence 4 private String name; 5 private int age; 6 public Person()  7 super(); 8 > 9 public Person(String name, int age)  10 super(); 11 this.name = name; 12 this.age = age; 13 > 14 @Override 15 public String toString()  16 return "Person [name=" + name + ", age=" + age + "]"; 17 > 18 public String getName()  19 return name; 20 > 21 public void setName(String name)  22 this.name = name; 23 > 24 public int getAge()  25 return age; 26 > 27 public void setAge(int age)  28 this.age = age; 29 > 30 >

Write a test class, first call WRITE () to write objects from memory to disk, then call read () to read objects from disk to memory

 1 import java.io.FileInputStream; 2 import java.io.FileNotFoundException; 3 import java.io.FileOutputStream; 4 import java.io.IOException; 5 import java.io.ObjectInputStream; 6 import java.io.ObjectOutput; 7 import java.io.ObjectOutputStream; 8 9 public class TestObjectOutputStream  10 11 public static void main(String[] args)  12 //write(); 13 read(); 14 > 15 16 public static void read()  17 //(1) Creating a stream object 18 ObjectInputStream ois = null; 19 try  20 ois = new ObjectInputStream(new FileInputStream("D:\\object.txt")); 21 //(2) Read the object 22 System.out.println(ois.readInt()); 23 System.out.println(ois.readUTF()); 24 System.out.println(ois.readObject()); 25 > catch (FileNotFoundException e)  26 // Todo automatically generated Catch block 27 e.printStackTrace(); 28 > catch (ClassNotFoundException e)  29 // Todo automatically generated Catch block 30 e.printStackTrace(); 31 > catch (IOException e)  32 // Todo automatically generated Catch block 33 e.printStackTrace(); 34 >finally  35 //(3) Close flow 36 if(ois != null)  37 try  38 ois.close(); 39 > catch (IOException e)  40 // Todo automatically generated Catch block 41 e.printStackTrace(); 42 > 43 > 44 > 45 > 46 47 //Write object 48 public static void write()  49 //(1) Creating an object stream object 50 ObjectOutputStream oos = null; 51 try  52 oos = new ObjectOutputStream(new FileOutputStream("D:\\object.txt")); 53 //(2) Write an object 54 oos.writeInt(999); 55 oos.writeUTF("shabi"); 56 oos.writeObject(new Person("ting",20)); 57 > catch (FileNotFoundException e)  58 // Todo automatically generated Catch block 59 e.printStackTrace(); 60 > catch (IOException e)  61 // Todo automatically generated Catch block 62 e.printStackTrace(); 63 >finally  64 //(3) Close flow 65 if(oos != null)  66 try  67 oos.close(); 68 > catch (IOException e)  69 // Todo automatically generated Catch block 70 e.printStackTrace(); 71 > 72 > 73 > 74 > 75 >

Serialization and reverse sequence

Serialization and reverse sequence
1) Elements that serialize
a) Cool member variables that can only save objects
b) You cannot save any member methods and static member variables (just saved attributes)
c) Does not save Transient member variables
d) If a member variable of an object is an object, this object is
Corporate variables will also be saved
e) Serialization is only the value of the variable, and for any modifier of the variable,
Can’t save

2) Use the object stream to write an object to the file, not only, not only the object is the order.
Limited, and member objects of the object must also be serialized.

3) If a serialized object contains an insequent objective object
Quote, then the entire serialization will fail and will throw a
NotserializableException. We can mark this reference as
TRANSIENT, the object is still serialized.

Write a small example

Create a Student class first, implement Serializable Interface, including name, age, school name (static modification), password (transient modification) attribute, and get () set () toString () has a parameter (parameter excluding SchoolName) and no parametric construction method

 1 import java.io.Serializable; 2 3 public class Student implements Serializable  4 /** 5 * 6 */ 7 private static final long serialVersionUID = -4502633718082654465L; 8 private String name; 9 private int age; 10 public static String schoolName;//School Name 11 private transient String pwd; //The value of the password attribute will no longer be serialized 12 public Student()  13 super(); 14 > 15 public Student(String name, int age, String pwd)  16 super(); 17 this.name = name; 18 this.age = age; 19 this.pwd = pwd; 20 > 21 public String getPwd()  22 return pwd; 23 > 24 public void setPwd(String pwd)  25 this.pwd = pwd; 26 > 27 public String getName()  28 return name; 29 > 30 public void setName(String name)  31 this.name = name; 32 > 33 public int getAge()  34 return age; 35 > 36 public void setAge(int age)  37 this.age = age; 38 > 39 @Override 40 public String toString()  41 return "Student [name=" + name + ", age=" + age + ", pwd=" + pwd + "]"+"schoolName="+schoolName; 42 > 43 >

Write a test class, first call WRITE () to write objects from memory to disk, then call read () to read objects from disk to memory

 1 import java.io.FileInputStream; 2 import java.io.FileNotFoundException; 3 import java.io.FileOutputStream; 4 import java.io.IOException; 5 import java.io.ObjectInputStream; 6 import java.io.ObjectOutputStream; 7 8 public class Test  9 public static void main(String[] args)  10 //Method for calling write objects 11 //write(); 12 //Method for calling the object 13 read(); 14 > 15 public static void write() 16 ObjectOutputStream oos=null; 17 try  18 oos=new ObjectOutputStream(new FileOutputStream("E:\\student.txt")); 19 Student stu=new Student("marry", 20, "888888"); 20 Student.schoolname = "JN Campus"; 21 oos.writeObject(stu); 22 > catch (FileNotFoundException e)  23 // TODO Auto-generated catch block 24 e.printStackTrace(); 25 > catch (IOException e)  26 // TODO Auto-generated catch block 27 e.printStackTrace(); 28 >finally 29 //closure 30 if(oos!=null) 31 try  32 oos.close(); 33 > catch (IOException e)  34 // TODO Auto-generated catch block 35 e.printStackTrace(); 36 > 37 > 38 > 39 > 40 public static void read() 41 ObjectInputStream ois=null; 42 try  43 ois=new ObjectInputStream(new FileInputStream("E:\\student.txt")); 44 Student stu=(Student) ois.readObject(); 45 System.out.println(stu); 46 //Result Output: Student [Name = Marry, Age = 20, PWD = NULL] SCHOOLNAME = NULL 47 //The PWD is empty because transient modifications Schoolname is empty because it is STATIC 48 > catch (FileNotFoundException e)  49 // TODO Auto-generated catch block 50 e.printStackTrace(); 51 > catch (ClassNotFoundException e)  52 // TODO Auto-generated catch block 53 e.printStackTrace(); 54 > catch (IOException e)  55 // TODO Auto-generated catch block 56 e.printStackTrace(); 57 >finally 58 //Shut down 59 if(ois!=null) 60 try  61 ois.close(); 62 > catch (IOException e)  63 // TODO Auto-generated catch block 64 e.printStackTrace(); 65 > 66 > 67 > 68 > 69 >

Object serialization precautions
1) Treatment of multiple serialization of the same object
a) All objects saved to the disk have a serialization number
b) Sequence in an object, first check if the object is already serialized

c) If not, serialize
d) If it is already serialized, it will no longer recombine, but the output number
I.e.

2) If you don’t want some attributes (sensitive) serialization, or do not want to recurrent
sequence
a) Add transient keywords to attribute (complete exclude in serialization)
b) Custom serialization (not only which attributes can not participate in serialization,
Can also define how the attribute is specific?

3) The serialized version is not compatible
a) After modifying the instance properties, it will affect the version number, resulting in anti-selecente
unsuccessful
b) Solutions: Typical version of the sequence version for Java
serialVersionUID

Источник

How to Ignore Properties Only For Serialization With Jackson

In this tutorial, we’re going to look at how we can ignore properties for serialization, but not for deserialization. So when Jackson is reading from JSON string, it will read the property and put into the target object. But when Jackson attempts to serialize the object, it will ignore the property.

2. Basic Usage for @JsonIgnoreProperties

The @JsonIgnoreProperties annotation lets us define ignored properties:

@Test public void shouldSerialize_WithIgnoreOnClass() throws JsonProcessingException < @JsonIgnoreProperties("name") class Person < private int age = 12; private String name = "john"; public int getAge() < return age; >public void setAge(int age) < this.age = age; >public String getName() < return name; >public void setName(String name) < this.name = name; >> Person person = new Person(); String json = objectMapper.writeValueAsString(person); assertThat(json).isEqualTo(""); >

Here, the name property is ignored and it is not in the JSON string. When we want to deserialize, the name property will also be ignored.

So we should follow a different way to make Jackson ignore a property during deserialization but not on serialization. Or vice versa.

3. allowGetters for Serialization-Only Object

Let’s investigate @JsonIgnoreProperties.

The @JsonIgnoreProperties annotation has allowGetters and allowSetters attributes.

When we set allowGetters as true, Jackson treats the object as read-only. In other words, Jackson will ignore the property for deserialization but will use it for serialization.

To illustrate the usage, we have the following Person class. Note that we have @JsonIgnoreProperties on the class definition and we’re setting allowGetters as true:

@JsonIgnoreProperties(value = "name", allowGetters = true) private static class Person < private int age; private String name; public int getAge() < return age; >public void setAge(int age) < this.age = age; >public String getName() < return name; >public void setName(String name) < this.name = name; >>

When we want to deserialize, the name property is ignored:

@Test public void shouldDeserialize_WithoutIgnored() throws IOException < final String json = ""; Person deserialized = objectMapper.readValue(json, Person.class); assertThat(deserialized.getName()).isNull(); assertThat(deserialized.getAge()).isEqualTo(12); >

So Jackson won’t deserialize the name property here.

Next, we’ll see what happens during serialization:

@Test public void shouldSerialize_WithIgnored() throws IOException < Person person = new Person(); person.setName("john"); person.setAge(12); String json = objectMapper.writeValueAsString(person); assertThat(json).isEqualTo(""); >

Here, Jackson doesn’t ignore the name property and serializes it.

4. allowSetters for Deserialization-Only Object

Now let’s continue with deserialization-only objects.

When we set allowSetters as true, Jackson treats the object as write-only. In other words, Jackson will ignore the property for serialization but will use it for deserialization.

We have a similar Person class. We’ve set allowSetters as true:

@JsonIgnoreProperties(value = "name", allowSetters = true) private static class Person < private int age; private String name; public int getAge() < return age; >public void setAge(int age) < this.age = age; >public String getName() < return name; >public void setName(String name) < this.name = name; >>

When we want to deserialize, Jackson won’t ignore the name property:

@Test public void shouldDeserialize_WithIgnored() throws IOException < final String json = ""; Person deserialized = objectMapper.readValue(json, Person.class); assertThat(deserialized.getName()).isEqualTo("john"); assertThat(deserialized.getAge()).isEqualTo(12); >

However, when we want to serialize, Jackson ignores the name property:

@Test public void shouldSerialize_WithoutIgnored() throws IOException < Person person = new Person(); person.setName("john"); person.setAge(12); String json = objectMapper.writeValueAsString(person); assertThat(json).isEqualTo(""); >

5. Summary

In this tutorial, we’ve detailed how to ignore properties only for serialization or deserialization.

Check out the source code for all examples over on Github.

Источник

Читайте также:  Bg color все цвета python
Оцените статью