<PlayListSettings>
<PlayList>
<id>PlayList1</Name>
<File class="string">/mnt/sdcard/Video1</File>
</PlayList>
</PlayListSettings>
This is my Serialized xml,where File is an arrayList of strings. I could remove the class="string" using xstream.aliasSystemAttribute(null, "class");
and the output is
<PlayListSettings>
<PlayList>
<id>PlayList1</Name>
<File>/mnt/sdcard/Video1</File>
</PlayList>
</PlayListSettings>
How do i deserialize using XStream?
You can use the #XStreamImplicit annotation for it. Here is a fully working example:
#XStreamAlias("PlayList")
public final class PlayList {
#XStreamImplicit(itemFieldName = "File")
private final List<String> files = new ArrayList<>();
public void addFile(final String file) {
checkFile(file);
files.add(file);
}
public void removeFile(final String file) {
checkFile(file);
files.remove(file);
}
public List<String> getFiles() {
return Collections.unmodifiableList(files);
}
private void checkFile(final String file) {
if (file == null) {
throw new NullPointerException();
} else if (file.isEmpty()) {
throw new IllegalArgumentException("is empty");
}
}
public static void main(String[] args) {
final PlayList playList = new PlayList();
playList.addFile("Foo");
playList.addFile("Bar");
// Serialize
final XStream xstream = new XStream();
xstream.autodetectAnnotations(true);
final String xml = xstream.toXML(playList);
System.out.println(xml);
// Deserialize
final PlayList playList2 = (PlayList) xstream.fromXML(xml);
for (final String file : playList.getFiles()) {
System.out.println(file);
}
}
}
The output looks like:
<PlayList>
<File>Foo</File>
<File>Bar</File>
</PlayList>
Related
I am using dropzone with Java Struts2. Before adding uploadMultiple:true to dropzone, server side working properly, i.e. getter and setter of File, FileName, and ContentType will be called accordingly. However after adding uploadMultiple:true, only the getter and setter of File are being called by the Struts interceptor.
I tried to change the param name and following these two website to do that, but no luck.
https://struts.apache.org/core-developers/file-upload-interceptor.html
https://www.mkyong.com/struts2/struts-2-upload-multiple-files-example/
//My JS
$("form#addrBookDropzone").dropzone(
{
url: "uploadData",
maxFilesize: maxFileSize,
maxFiles: 10,
acceptedFiles: ".csv",
addRemoveLinks: true,
autoProcessQueue: false,
uploadMultiple:true,
parallelUploads: 10,
paramName:'csvFile',
init: function (e) {
abDropzone = this;
abDropzone.processQueue();
},
success: function(file, response){
retrieveCsvTransition();
}
}
);
//My Java
public class FileProcessor extends ActionSupport{
private static final long serialVersionUID = -234712913575630908L;
public static final Logger logger = Logger.getLogger(FileProcessor.class);
private String className = this.getClass().getSimpleName();
private List<File> csvFile = new ArrayList<File>();
private List<String> csvFileContentType = new ArrayList<String>();
private List<String> csvFileFileName = new ArrayList<String>();
private Set<TblCsvTransition> csvData = new HashSet<TblCsvTransition>(0);
private AbstractMap<String, File> fileMap = new HashMap<String, File>(0);
public List<File> getCsvFile() {
return csvFile;
}
public void setCsvFile(List<File> csvFile) {
this.csvFile = csvFile;
}
public List<String> getCsvFileContentType() {
return csvFileContentType;
}
public void setCsvFileContentType(List<String> csvFileContentType) {
this.csvFileContentType = csvFileContentType;
}
public List<String> getCsvFileFileName() {
return csvFileFileName;
}
public void setCsvFileFileName(List<String> csvFileFileName) {
this.csvFileFileName = csvFileFileName;
}
}
I couldn't figure why struts not passing file names, in the end I can only comment out parallelUploads and passing the file names as param
public class bean {
private String name;
private String[] friends;
}
public void createSuperCSVFile(final List<VariantTO> data,
final File file) throws IOException {
ICsvBeanWriter beanWriter = null;
try {
String[] header = {"name", "friends"};
beanWriter = new CsvBeanWriter(new FileWriter(file), TAB_PREFERENCE);
// write the header
beanWriter.writeHeader(header);
for (Object object: data) {
beanWriter.write(object, header);
}
} finally {
if( beanWriter != null ) {
beanWriter.close();
}
}
}
I am using supercsv to write a POJO with an attribute containing string array to csv. The CsvBeanWriter simply writes the object address instead of its value in the column. Is there any settings to map the value correctly?
EXPECTED
name friends
john dimitry,olaf,nett
ACTUAL
name friends
john [Ljava.lang.String;#50ccb5a3
The solution was to write my own cell processor. I wrote a String[] processor, which returns a comma separated value as a string.
final CellProcessor[] PROCESSORS = new CellProcessor[] {
new NotNull(),
new ParseStringArray()
};
beanWriter = new CsvBeanWriter(new FileWriter(file), TAB_PREFERENCE);
for (Object object: data) {
beanWriter.write(object, header, PROCESSORS);
}
class ParseStringArray extends CellProcessorAdaptor implements StringCellProcessor {
#Override
public <T> T execute(final Object value, final CsvContext context) {
validateInputNotNull(value, context);
String result;
if (value instanceof String[]) {
result = StringUtils.join((String[]) value, ",");
} else {
final String actualClassName = value.getClass().getName();
throw new SuperCsvCellProcessorException(String.format(
"the input value should be of type String array but is of type %s", actualClassName), context, this);
}
return next.execute(result, context);
}
}
I want to save my Object Mall into XML, however it doesn't seem to save when I open the XML file. Is it because there are too many objects within the Mall class to be saved therefore it can't be saved?
Below are my codes :
Mall Class
public class Mall implements ActionExecute,Serializable {
private static Mall singleton = null;
private ArrayList<Store> storeList = new ArrayList ();
private ArrayList<Customer> customerList = new ArrayList ();
public static Mall instance()
{
if(singleton == null)
{
singleton = new Mall();
}
return singleton;
}
public void createStore(String factory,String storeType,String storeName)
{
AbstractFactory Factory = FactoryProducer.getFactory(factory);
if(factory.equals("store"))
{
Store newstore = Factory.getStore(storeType,storeName);
storeList.add(newstore);
}
}
SaveFile Class
public class saveFile {
public static void write(Mall f) throws Exception{
try (XMLEncoder encoder = new XMLEncoder(
new BufferedOutputStream(
new FileOutputStream("designpattern.xml")))) {
encoder.writeObject(f);
}
}
}
XML file Result
<?xml version="1.0" encoding="UTF-8"?>
<java version="1.7.0_25" class="java.beans.XMLDecoder">
<object class="designpattern.Mall"/>
</java>
I have the following bean:
public class ContractBean {
private List<String> listNd;
private String nd;
public List<String> getListNd() {
return listNd;
}
public void setListNd(final List<String> listNd) {
this.listNd = listNd;
}
public String getNd() {
return nd;
}
public void setNd(final String nd) {
this.nd= nd;
}
}
I use apache Betwixt to output XML from my bean.
final BeanWriter beanWriter = new BeanWriter(outputWriter);
beanWriter.getXMLIntrospector().getConfiguration().setAttributesForPrimitives(false);
beanWriter.getBindingConfiguration().setMapIDs(false);
beanWriter.enablePrettyPrint();
beanWriter.setWriteEmptyElements(false);
beanWriter.getBindingConfiguration().setObjectStringConverter(new CustomObjectStringConverter());
beanWriter.write(obj);
The listND attribute of my bean is null, but i still get:
<contract>
<listNd/>
<nd>22222</nd>
</contract>
How can I remove empty lists from the output XML ?
This question already has an answer here:
Closed 12 years ago.
Possible Duplicate:
Convert all node's attributes into child nodes
I would like to convert xml attributes to tag. for e.g. Using XStream
<root>
<abc attr1="aaa" attr2="bbb"/>
</root>
TO
<root>
<abc>
<attr1>aaa</attr1>
<attr2>bbb</attr2>
</abc>
</root>
Any pointers would be helpful.
It is not possible to convert it directly as long as XStream is used. If you want to use XStream, it is necessary to make the class that corresponds to the element of XML.
[to read]
XStream xs = new XStream(new DomDriver());
xs.alias("root", ParentElement.class);
xs.useAttributeFor(ChildElement.class, "aaa"); // read as attribute
xs.useAttributeFor(ChildElement.class, "bbb");
ParentElement parent = new ParentElement();
try {
FileInputStream fis = new FileInputStream("readfile");
xs.fromXML(fis, parent);
} catch (FileNotFoundException ex) {
ex.printStackTrace();
}
[to write]
ChildElement element = new ChildElement();
element.setAttr1("aaa");
element.setAttr2("bbb");
ParentElement parent = new ParentElement();
parent.setChildElement(element);
XStream xs = new XStream();
xs.alias("root", ParentElement.class);
try {
FileOutputStream fs = new FileOutputStream("writefile");
xs.toXML(parent, fs);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
[ParentElement]
public class ParentElement {
private ChildElement abc;
public void setChildElement(ChildElement child) {
this.abc = child;
}
}
[ChildElement]
public class ChildElement {
private String attr1;
private String attr2;
public String getAttr1() {
return attr1;
}
public void setAttr1(String attr1) {
this.attr1 = attr1;
}
public String getAttr2() {
return attr2;
}
public void setAttr2(String attr2) {
this.attr2 = attr2;
}
}