2

I want to serialize an arraylist of Item but it doesn't work....

my Item class extends Stuff class and has some subclasses.

all of my classes implement Serilalizable.

i have this part :

try{
// Serialize data object to a file
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("MyData.ser"));
out.writeObject(myData);
out.close();

// Serialize data object to a byte array
ByteArrayOutputStream bos = new ByteArrayOutputStream() ;
out = new ObjectOutputStream(bos) ;
out.writeObject(myData);
out.close();

// Get the bytes of the serialized object
byte[] buf = bos.toByteArray();
} catch (IOException e) {
}

my classes :

public class Stuff implements Serializeable{
....
some protected fields
.
.
}

public class Item extends Stuff implements Serializable{
...
..
.
} and some subclasses of Item:

public class FirstItem extends Item implements Serializable{
...
}

public class SecondItem extends Item implements Serializable{
...
} ... I want to serialize an object contains ArrayList of <Item> that has objects of Item's subclasses (FirstItem,SecondItem,...)

i think informations are sufficient...

it's just a little mistake and now works correctly... I'm sorry for my stupid question.

Thank you for your answers.

armin.mohammadi
  • 75
  • 1
  • 3
  • 8

2 Answers2

6

You can serialize class of ArrayList like this

public class MyData implements Serializable {

    private long id;
    private String title;
    private ArrayList<String> tags;
    ...

    public String getTitle() {
    }
}

And to create serializable

    ArrayList<MyData> myData = new ArrayList<MyData>();

try{
    // Serialize data object to a file
    ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("MyData.ser"));
    out.writeObject(myData);
    out.close();

    // Serialize data object to a byte array
    ByteArrayOutputStream bos = new ByteArrayOutputStream() ;
    out = new ObjectOutputStream(bos) ;
    out.writeObject(myData);
    out.close();

    // Get the bytes of the serialized object
    byte[] buf = bos.toByteArray();
} catch (IOException e) {
}
Sardor I.
  • 416
  • 4
  • 8
1

I'm taking a leap here that you are trying to serialize to something like json?

if so, you can use jackson (http://jackson.codehaus.org/)

final ObjectMapper mapper = new ObjectMapper();
try
{
    final String jsonString = mapper.writeValueAsString( _integrationSettings );
    // do something with the string...
}
catch( IOException e )
{
    // use a logger to output error
}

You can also deserialize with jackson as well...

A more detailed example here: http://blog.inflinx.com/2012/05/10/using-jackson-for-javajson-conversion/

Note: you can do similar for XML.

Christien Lomax
  • 105
  • 2
  • 5