1

Given the following classes:

public class Container {
    private List<SomeData> list;
    // public getter & setter for list
}

public class SomeData {
    private String data;
   // public getter & setter for data
}

When I run the following code:

import java.beans.XMLEncoder;
import java.io.FileOutputStream;

SomeData someData1 = new SomeData();
SomeData someData2 = new SomeData();

someData1.setData("data1");
someData2.setData("data2");

List<SomeData> data = new ArrayList<SomeData>();
data.add(someData1);
data.add(someData2);

Container container = new Container();
container.setList(data); 

FileOutputStream os = new FileOutputStream("c:\test.xml");
XMLEncoder encoder = new XMLEncoder(os);
encoder.writeObject(container);
encoder.close();

When I review 'test.xml', there is only data for the container object, and nothing for the SomeData objects in the list (i.e. the strings "data1" & "data2"):

<?xml version="1.0" encoding="UTF-8"?> 
<java version="1.6.0_22" class="java.beans.XMLDecoder"> 
 <object class="Container"> 
  <void property="container"> 
   <object class="java.util.ArrayList"> 
    <void method="add"> 
     <object class="SomeData"/> 
    </void> 
    <void method="add"> 
     <object class="SomeData"/> 
    </void> 
   </object> 
  </void> 
 </object> 
</java> 

How can I serialize 'container' and the SomeData objects stored in the list within 'container'?

skaffman
  • 398,947
  • 96
  • 818
  • 769
TERACytE
  • 7,553
  • 13
  • 75
  • 111
  • Well, there is clearly something there, two instances of `SomeData`, but their fields are missing. – biziclop Jan 27 '11 at 22:52
  • FYI: this works fine on my machine. Also, I think your code is inconsistent with example output. In output you have property 'container' under Container, but in example code - the name of property is 'list'. So check your code for 'SomeData' fields setting. – Art Licis Jan 27 '11 at 22:53
  • Yea - I created the above example by hand, so there may be errors. If it works fine on your machine, you mean you get the strings "data1" & "data2" in the xml? Is the code exactly the same as above, or did you tweak it? – TERACytE Jan 27 '11 at 23:26
  • Oddly enough the code I wrote above does work, despite being almost identical to the original. Time to break out the diff tool. – TERACytE Jan 27 '11 at 23:32

1 Answers1

0

The code works fine for me as long as I provide getter for SomeData.data named according to the java beans naming convention:

SomeData.getData()

If I change the name of the getter, the serialization wont work.

Pekkasso
  • 419
  • 2
  • 8
  • I'm not sure what I did since the code I have is the same (save for name changes) as what I posted. I basically rewrote the code and it worked! Clearly I missed something. Than-you for your feedback. – TERACytE Jan 31 '11 at 23:48