Reputation: 744
Is there any way to serialize some fields with different name? For example I have a class as follows:
public class MyClass implements Serializeable {
private String name;
private String lastName;
}
And I want it to be serialized, but also want the field name
be renamed to a1
and field lastName
be renamed to a2
.
Actually my app provides a hessian web service. As far as I know hessian uses java serialization for serializing objects and stream them to client.
Upvotes: 3
Views: 2181
Reputation: 2001
I highly recommend to use some sort of data format like XML or JSON, which will make your task much easier since you can write your custom "(de-)serializers" to perform the transformation for you.
If you need to work with Javas object serialization, you need both classes to have the same class name (package name and class name) and additionally have a serialVersionUID attached to it with the same value in order for the class serialization to read the class back.
package testbench;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
public class MyClass implements Serializable {
private static final long serialVersionUID = 1L;
private String name;
private String lastName;
public MyClass(final String name, final String lastName) {
this.name = name;
this.lastName = lastName;
}
private void writeObject(final ObjectOutputStream out) throws IOException {
out.writeUTF(name);
out.writeUTF(lastName);
}
private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException {
name = in.readUTF();
lastName = in.readUTF();
}
@Override
public String toString() {
return name + " " + lastName;
}
}
The client can use a different class with other methods and fields:
package testbench;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
public class MyClass implements Serializable {
private static final long serialVersionUID = 1L;
private String a1;
private String a2;
public MyClass(final String a1, final String a2) {
this.a1 = a1;
this.a2 = a2;
}
private void writeObject(final ObjectOutputStream out) throws IOException {
out.writeUTF(a1);
out.writeUTF(a2);
}
private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException {
a1 = in.readUTF();
a2 = in.readUTF();
}
@Override
public String toString() {
return a1 + " " + a2;
}
}
Upvotes: 2