I have some problems when trying to deserialize a list of objects. I have searialized a list of objects into a .dat file. If I want to retrieve the data from that file later, when I try to deserialize that list I don’t get the desired result. Here is the code.
Serialization:
MyFile mf = new MyFile("2012-12-18.dat");
mf.Open();
FileOutputStream fos = mf.GetOS();
Iterator<Element> currencies = cube.select("Rate").iterator();
ISerializare[] lista = new ISerializare[31];
int i=0;
while (currencies.hasNext()){
MyCurrency newCurrency=new MyCurrency();
Element newElement=currencies.next();
newCurrency.setSymbol(newElement.attr("currency"));
newCurrency.setValue(Double.parseDouble(newElement.text()));
lista[i] = newCurrency;
System.out.println(newCurrency.toString());
i++;
}
DataOutputStream dos = new DataOutputStream(fos);
for(int j=0;j<i;j++){
lista[j].ObjectSerialization(dos);
}
dos.close();
public class MyFile {
File fisier;
String name;
public MyFile(String n){
name = n;
}
public void Open(){
fisier = new File(name);
}
public FileOutputStream GetOS() throws IOException{
return new FileOutputStream(fisier);
}
public FileInputStream GetIS() throws IOException{
return new FileInputStream(fisier);
}
}
MyFile mf = new MyFile("2012-12-18.dat");
mf.Open();
FileInputStream fis = mf.GetIS();
DataInputStream dis = new DataInputStream(fis);
for(ISerialization element:list){
element.ObjectDeserialization(dis);
System.out.println(element.toString());
and here is MyCurency class:
public class MyCurrency implements ISerialization
{
private String symbol;
private double value;
public String getSymbol() {
return symbol;
}
public void setSymbol(String symbol) {
this.symbol = symbol;
}
public double getValue() {
return value;
}
public void setValue(double value) {
this.value = value;
}
public String toString(){
return symbol +" = "+value + " RON";
}
@Override
public void ObjectSerialization(DataOutputStream dos) throws IOException {
dos.writeDouble(value);
}
@Override
public void ObjectDeserialization(DataInputStream dis) throws IOException {
value = dis.readDouble();
}
Can you please tell me what is wrong?
There are lots of things which could be wrong. Since you are not specific I will have to use my imagination.
The method names don’t follow Java Coding Conventions which doesn’t make them easy to read. Using a code formatter would help.
The most obvious issue is that you only write the
valuefield which means thesymbolwill benullafter you deserialize it.Also
is the same as
And
has no formatting for value so it might print YEN 100.0 or USD 100.0 when it should be YEN 100 and USD 100.00 and it’s not obvious why you have ” RON” at the end.
If it helps at all, this is how I would write it