I want to unmarshal this xml
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<response>
<command>dir</command>
<directory name="folder">
<file>
<lastModified>2016-06-06 12:45 AM</lastModified>
<name>input.txt</name>
<size>123</size>
<type>file</type>
</file>
<file>
<lastModified>2016-06-06 12:45 AM</lastModified>
<name>data.txt</name>
<size></size>
<type>directory</type>
</file>
</directory>
</response>
here is my class structure
import java.util.ArrayList;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlSeeAlso;
#XmlRootElement
#XmlSeeAlso({MessageResponse.class})
class Response {
String command;
public Response() {
}
#XmlElement
public String getCommand() {
return command;
}
public void setCommand(String command) {
this.command = command;
}
}
#XmlRootElement
class MessageResponse extends Response{
String message;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
class DirListingResponse extends Response{
String name;
Directory directory;
#XmlElement
public Directory getDirectory() {
return directory;
}
public void setDirectory(Directory directory) {
this.directory = directory;
}
}
class Directory {
ArrayList<File> file;
String name;
public Directory() {
}
#XmlAttribute
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#XmlElement
public ArrayList<File> getFile() {
return file;
}
public void setFile(ArrayList<File> file) {
this.file = file;
}
}
class File {
String name, type;
String lastModified;
long size;
public File() {
}
public File(String name, String type, String lastModified, long size) {
this.name = name;
this.type = type;
this.lastModified = lastModified;
this.size = size;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getLastModified() {
return lastModified;
}
public void setLastModified(String lastModified) {
this.lastModified = lastModified;
}
public long getSize() {
return size;
}
public void setSize(long size) {
this.size = size;
}
}
and the main class
try {
jaxbContext = JAXBContext.newInstance(Response.class);
jaxbUnmarshaller = jaxbContext.createUnmarshaller();
Object obj = jaxbUnmarshaller.unmarshal(new InputSource(new StringReader(inputXml)));
} catch (JAXBException e) {
e.printStackTrace();
}
but this is not working accordingly. obj contains only command field of response class due to not the proper annotation. Under "response" tag "directory" and "message" tag appears based on command fired. If the command is "dir" then "directory" tag otherwise "message" tag. So I want this unmarshal and save the result in relative inherited class. How can I solve this ?
One solution although not elegant is to
read the input XML beforehand and check if it has <directory or <message
accordingly instantiate the jaxbcontext.
jaxbContext = JAXBContext.newInstance(MessageResponse.class);
or
jaxbContext = JAXBContext.newInstance(DirListingResponse.class);
I have a solution which uses the Sax-Parser. I uploaded it to Github. There should be better solutions (including implicit typings). But this would solve your problems, while creating new ones. Changes to File and Directory, etc. would introduce changes in the corresponding handlers...
Related
I have the following XML:
<game name="m1itskow" sourcefile="maygay1bsw.c" ismechanical="yes" cloneof="m1itsko" romof="m1itsko">
<description>It's A Knockout (Maygay) (M1A/B) (set 24)</description>
<year>199?</year>
<manufacturer>Maygay</manufacturer>
</game>
Today I have manufacturer as a String inside Game class, but I need to map to a Manufacturer class, how should I do it? Is it possible? thanks.
edit: The XML cannot be changed because this is a generated file by a 3rd party tool.
Made changes in xml structure
XML
<?xml version="1.0" encoding="UTF-8"?>
<game name="m1itskow" sourcefile="maygay1bsw.c" ismechanical="yes" cloneof="m1itsko" romof="m1itsko">
<description>It's A Knockout (Maygay) (M1A/B) (set 24)</description>
<year>199?</year>
<manufacturer>
<manufacturer-name>Maygay</manufacturer-name>
</manufacturer>
</game>
POJO game and manufacturer...
game.java
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement
public class game {
private String name;
private String sourcefile;
private String ismechanical;
private String cloneof;
private String romof;
private String description;
private String year;
private Manufacturer manufacturer=new Manufacturer();
public game() {}
#XmlAttribute
public String getIsmechanical() {
return ismechanical;
}
public void setIsmechanical(String ismechanical) {
this.ismechanical = ismechanical;
}
#XmlAttribute
public String getCloneof() {
return cloneof;
}
public void setCloneof(String cloneof) {
this.cloneof = cloneof;
}
#XmlAttribute
public String getRomof() {
return romof;
}
public void setRomof(String romof) {
this.romof = romof;
}
#XmlAttribute
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#XmlAttribute
public String getSourcefile() {
return sourcefile;
}
public void setSourcefile(String sourcefile) {
this.sourcefile = sourcefile;
}
#XmlElement
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
#XmlElement
public String getYear() {
return year;
}
public void setYear(String year) {
this.year = year;
}
#XmlElement(name="manufacturer")
public Manufacturer getManufacturer() {
return manufacturer;
}
public void setManufacturer(Manufacturer manufacturer) {
this.manufacturer=manufacturer;
}
}
manufacturer.java
i
mport java.io.Serializable;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement(name="manufacturer")
public class Manufacturer implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private String Name;
#XmlElement(name="manufacturer-name")
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
}
main.java
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
public class SampleTest {
public static void main(String[] args) {
try {
File file = new File("employee.xml");
JAXBContext jaxbContext = JAXBContext.newInstance(game.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
game e=(game) jaxbUnmarshaller.unmarshal(file);
System.out.println(e.getManufacturer().getName());
}
catch (JAXBException e) {
e.printStackTrace();
}
}
}
This is my class structure:
#XmlRootElement(name="System")
public class SystemDTO () {
#XmlElement(name="ID")
public void setId(String id) {
this.id = id;
}
#XmlElement(name="Source")
public void setSource(SourceDTO source) {
this.source = source;
}
}
#XmlRootElement(name="Source")
class SourceDTO {
#XmlElement(name="Name")
public void setName(String name) {
this.name = name;
}
}
This is my XML File:
<System>
<ID>e5b160d0</ID>
<Source>
<Name>Kron</Name>
</Source>
</System>
The problem is the Source is always null. I do not get a exception, it just comes out null. I've attempted to use just the Source tag and it picks up Name just fine, but when I add it as part of the System class it does not seem to work.
Additionally I attempted to do this and have a string member variable in System for name:
#XmlElementWrapper(name="Source")
#XmlElement(name="Name")
But that causes an exception. Any ideas?
The Test Class
public class JaxbTest {
public static void main(String[] args) {
String xml = "<System>\n" +
" <ID>e5b160d0</ID>\n" +
" <Source>\n" +
" <Name>Kron</Name>\n" +
" </Source>\n" +
"</System>";
SystemDTO systemDTO;
try {
JAXBContext jaxbContext = JAXBContext.newInstance(SystemDTO.class);
StringReader reader = new StringReader(xml);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
systemDTO = (SystemDTO) jaxbUnmarshaller.unmarshal(reader);
System.out.println(systemDTO.getSource().getName());
} catch (JAXBException e) {
e.printStackTrace();
}
}
}
Source DTO
#XmlRootElement(name = "Source")
class SourceDTO {
private String name = null;
public String getName() {
return name;
}
#XmlElement(name = "Name")
public void setName(String name) {
this.name = name;
}
}
System DTO
#XmlRootElement(name = "System")
public class SystemDTO {
private String id;
private SourceDTO source;
public String getId() {
return id;
}
public SourceDTO getSource() {
return source;
}
#XmlElement(name = "ID")
public void setId(String id) {
this.id = id;
}
#XmlElement(name = "Source")
public void setSource(SourceDTO source) {
this.source = source;
}
}
One possible problem that I see is that you have declared 2 "Root" elements in your XML. Try #XmlType on your Source class:
#XmlType(name="Source")
class SourceDTO {
...
}
I am trying to read an XML file from java program. I am able to read its contents.I am posting the XML file from which i am reading contents.
<?xml version="1.0" encoding="UTF-8" ?>
<customer id="100">
<age>29</age>
<name>lucifer</name>
</customer>
i am able to write its contents through java program i am posting my code..
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement
public class Customer {
String name;
int age;
int id;
public String getName() {
return name;
}
#XmlElement
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
#XmlElement
public void setAge(int age) {
this.age = age;
}
public int getId() {
return id;
}
#XmlAttribute
public void setId(int id) {
this.id = id;
}
}
public class CheckClass {
public static void main(String[] args) {
try {
File file = new File("./file/NewFile.xml");
JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
Customer customer = (Customer) jaxbUnmarshaller.unmarshal(file);
System.out.println(customer.age);
} catch (JAXBException e) {
e.printStackTrace();
}
}
}
But i have to read values from this XML file which i can not.This is my XML file
<?xml version="1.0" encoding="UTF-8"?>
<DBConfig ID="1" Name ="" DriverName="" HostName="localhost" PortName="" DBName="" ServiceName="" User="" PassWord="" sid="">
<TableConfig ID= "1" TableName="">
</TableConfig>
</DBConfig>
When i am trying to access this xml values through java class i am getting this error..
com.sun.xml.internal.bind.v2.runtime.IllegalAnnotationsException: 2 counts of IllegalAnnotationExceptions
Class has two properties of the same name "DBName"
this problem is related to the following location:
at public java.lang.String com.gamma.DBConf.getDBName()
at com.gamma.DBConf
this problem is related to the following location:
at public java.lang.String com.gamma.DBConf.DBName
at com.gamma.DBConf
Class has two properties of the same name "sid"
this problem is related to the following location:
at public java.lang.String com.gamma.DBConf.getSid()
at com.gamma.DBConf
this problem is related to the following location:
at public java.lang.String com.gamma.DBConf.sid
at com.gamma.DBConf
at com.sun.xml.internal.bind.v2.runtime.IllegalAnnotationsException$Builder.check(Unknown Source)
at com.sun.xml.internal.bind.v2.runtime.JAXBContextImpl.getTypeInfoSet(Unknown Source)
at com.sun.xml.internal.bind.v2.runtime.JAXBContextImpl.<init>(Unknown Source)
at com.sun.xml.internal.bind.v2.runtime.JAXBContextImpl.<init>(Unknown Source)
at com.sun.xml.internal.bind.v2.runtime.JAXBContextImpl$JAXBContextBuilder.build(Unknown Source)
at com.sun.xml.internal.bind.v2.ContextFactory.createContext(Unknown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at javax.xml.bind.ContextFinder.newInstance(Unknown Source)
at javax.xml.bind.ContextFinder.newInstance(Unknown Source)
at javax.xml.bind.ContextFinder.find(Unknown Source)
at javax.xml.bind.JAXBContext.newInstance(Unknown Source)
at javax.xml.bind.JAXBContext.newInstance(Unknown Source)
at com.gamma.ReadXML.main(ReadXML.java:22)
and this is my java classes
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement
public class DBConf {
public String Name;
public String DriverName;
public String HostName;
public String PortName;
public String DBName;
public String ServiceName;
public String User;
public String PassWord;
public String sid;
public String getName() {
return Name;
}
#XmlElement
public void setName(String name) {
Name = name;
}
public String getDriverName() {
return DriverName;
}
#XmlElement
public void setDriverName(String driverName) {
DriverName = driverName;
}
public String getHostName() {
return HostName;
}
#XmlElement
public void setHostName(String hostName) {
HostName = hostName;
}
public String getPortName() {
return PortName;
}
#XmlElement
public void setPortName(String portName) {
PortName = portName;
}
public String getDBName() {
return DBName;
}
#XmlElement
public void setDBName(String dBName) {
DBName = dBName;
}
public String getServiceName() {
return ServiceName;
}
#XmlElement
public void setServiceName(String serviceName) {
ServiceName = serviceName;
}
public String getUser() {
return User;
}
#XmlElement
public void setUser(String user) {
User = user;
}
public String getPassWord() {
return PassWord;
}
#XmlElement
public void setPassWord(String passWord) {
PassWord = passWord;
}
public String getSid() {
return sid;
}
#XmlElement
public void setSid(String sid) {
this.sid = sid;
}
}
And this is the main class
public class ReadXML {
/**
* #param args
*/
public static void main(String[] args) {
try {
File file = new File("./file/dbconfig.xml");
JAXBContext jaxbContext = JAXBContext.newInstance(DBConf.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
DBConf db = (DBConf) jaxbUnmarshaller.unmarshal(file);
System.out.println(db.HostName);
} catch (JAXBException e) {
e.printStackTrace();
}
}
}
can anyone help
Note that you are annotating Attribute as Element. Fix that.
Even after that if problem occurs -
Try using - #XmlAccessorType(XmlAccessType.FIELD)
Move #XmlAttribute(name = "HostName") annotations to fields instead of accessor methods.
I am not sure if this is your problem. I faced a similar problem and this helped me. I wont guarantee that it will solve your problem but prima facie, it appears that above can fix it.
dbName, sid are Attributes, but you have annotated them #XmlElement. change all the attributes to #XmlAttribute.
Why don't you use
Xstream library
Example:
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.annotations.XStreamAsAttribute;
#XStreamAlias("Cat")
class Cat {
#XStreamAsAttribute
int age;
String name;
}
public class XStreamDemo {
public static void main(String[] args) {
XStream xstream = new XStream();
xstream.processAnnotations(Cat.class);
String xml = "<Cat age='4' ><name>Garfield</name></Cat>";
Cat cat = (Cat) xstream.fromXML(xml);
System.out.println("name -> " + cat.name);
System.out.println("age -> " + cat.age);
}
}
You need to add Xstream jar files in to classpath.
Use these classes.
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "", propOrder = {
"value"
})
#XmlRootElement(name = "TableConfig")
public class TableConfig {
#XmlValue
protected String value;
#XmlAttribute(name = "ID")
protected Byte id;
#XmlAttribute(name = "TableName")
protected String tableName;
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public Byte getID() {
return id;
}
public void setID(Byte value) {
this.id = value;
}
public String getTableName() {
return tableName;
}
public void setTableName(String value) {
this.tableName = value;
}
}
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "", propOrder = {
"tableConfig"
})
#XmlRootElement(name = "DBConfig")
public class DBConfig {
#XmlElement(name = "TableConfig", required = true)
protected TableConfig tableConfig;
#XmlAttribute(name = "ID")
protected Byte id;
#XmlAttribute(name = "Name")
protected String name;
#XmlAttribute(name = "DriverName")
protected String driverName;
#XmlAttribute(name = "HostName")
protected String hostName;
#XmlAttribute(name = "PortName")
protected String portName;
#XmlAttribute(name = "DBName")
protected String dbName;
#XmlAttribute(name = "ServiceName")
protected String serviceName;
#XmlAttribute(name = "User")
protected String user;
#XmlAttribute(name = "PassWord")
protected String passWord;
#XmlAttribute
protected String sid;
public TableConfig getTableConfig() {
return tableConfig;
}
public void setTableConfig(TableConfig value) {
this.tableConfig = value;
}
public Byte getID() {
return id;
}
public void setID(Byte value) {
this.id = value;
}
public String getName() {
return name;
}
public void setName(String value) {
this.name = value;
}
public String getDriverName() {
return driverName;
}
public void setDriverName(String value) {
this.driverName = value;
}
public String getHostName() {
return hostName;
}
public void setHostName(String value) {
this.hostName = value;
}
public String getPortName() {
return portName;
}
public void setPortName(String value) {
this.portName = value;
}
public String getDBName() {
return dbName;
}
public void setDBName(String value) {
this.dbName = value;
}
public String getServiceName() {
return serviceName;
}
public void setServiceName(String value) {
this.serviceName = value;
}
public String getUser() {
return user;
}
public void setUser(String value) {
this.user = value;
}
public String getPassWord() {
return passWord;
}
public void setPassWord(String value) {
this.passWord = value;
}
public String getSid() {
return sid;
}
public void setSid(String value) {
this.sid = value;
}
}
I am using JAXB2 to serialize object to xml.
Is there any way how to force it to create entire object structure like in following example even if it is not filled in backing object?
This is my intended result even without having asignee property set.
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<note>
<to xsi:nil="true"/>
<from xsi:nil="true"/>
<header xsi:nil="true"/>
<body>text</body>
<assignee>
<name xsi:nil="true"/>
<surname xsi:nil="true"/>
</assignee>
</note>
I use following code for serialization:
JAXBContext jc = JAXBContext.newInstance(dataObject.getClass());
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.setProperty(Marshaller.JAXB_SCHEMA_LOCATION, schemaLocation);
marshaller.setProperty(Marshaller.JAXB_ENCODING, charset);
marshaller.marshal(dataObject, outputStream);
You can do the following:
Note
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
#XmlRootElement
#XmlType(propOrder={"to", "from", "header", "body", "assignee"})
public class Note {
private String to;
private String from;
private String header;
private String body;
private Assignee assignee;
#XmlElement(nillable=true)
public String getTo() {
return to;
}
public void setTo(String to) {
this.to = to;
}
#XmlElement(nillable=true)
public String getFrom() {
return from;
}
public void setFrom(String from) {
this.from = from;
}
#XmlElement(nillable=true)
public String getHeader() {
return header;
}
public void setHeader(String header) {
this.header = header;
}
#XmlElement(nillable=true)
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
public Assignee getAssignee() {
return assignee;
}
public void setAssignee(Assignee assignee) {
this.assignee = assignee;
}
}
Assignee
We will need to have a means to no when an unmarshalled instance of Assignee should be interpreted as null. I have added an isNull() method that returns true if all the fields are null.
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
#XmlJavaTypeAdapter(AssigneeAdapter.class)
public class Assignee {
private String name;
private String surname;
#XmlElement(nillable=true)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#XmlElement(nillable=true)
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public boolean isNull() {
return null == name && null == surname;
}
}
AssigneeAdapter
The AssigneeAdapter uses both the Assignee object for the value type and bound type. This class leverages the isNull() method we added on Assignee:
import javax.xml.bind.annotation.adapters.XmlAdapter;
public class AssigneeAdapter extends XmlAdapter<Assignee, Assignee> {
#Override
public Assignee unmarshal(Assignee v) throws Exception {
if(v.isNull()) {
return null;
}
return v;
}
#Override
public Assignee marshal(Assignee v) throws Exception {
if(null == v) {
return new Assignee();
}
return v;
}
}
Demo
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Note.class);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(new Note(), System.out);
}
}
For more information on XmlAdapter see:
http://bdoughan.blogspot.com/2010/07/xmladapter-jaxbs-secret-weapon.html
http://bdoughan.blogspot.com/2010/12/jaxb-and-immutable-objects.html
Yes. Use a combination of #XmlElementRef and JAXBElement with nil set to true.
See:
http://download.oracle.com/javase/6/docs/api/javax/xml/bind/JAXBElement.html
http://download.oracle.com/javaee/6/api/javax/xml/bind/annotation/XmlElementRef.html
Here is my class,
public class FreebasePeopleResults {
public String intendedSearch;
public String weight;
public Double heightMeters;
public Integer age;
public String type;
public String parents;
public String profession;
public String alias;
public String children;
public String siblings;
public String spouse;
public String degree;
public String institution;
public String wikipediaId;
public String guid;
public String id;
public String gender;
public String name;
public String ethnicity;
public String articleText;
public String dob;
public String getWeight() {
return weight;
}
public void setWeight(String weight) {
this.weight = weight;
}
public Double getHeightMeters() {
return heightMeters;
}
public void setHeightMeters(Double heightMeters) {
this.heightMeters = heightMeters;
}
public String getParents() {
return parents;
}
public void setParents(String parents) {
this.parents = parents;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getProfession() {
return profession;
}
public void setProfession(String profession) {
this.profession = profession;
}
public String getAlias() {
return alias;
}
public void setAlias(String alias) {
this.alias = alias;
}
public String getChildren() {
return children;
}
public void setChildren(String children) {
this.children = children;
}
public String getSpouse() {
return spouse;
}
public void setSpouse(String spouse) {
this.spouse = spouse;
}
public String getDegree() {
return degree;
}
public void setDegree(String degree) {
this.degree = degree;
}
public String getInstitution() {
return institution;
}
public void setInstitution(String institution) {
this.institution = institution;
}
public String getWikipediaId() {
return wikipediaId;
}
public void setWikipediaId(String wikipediaId) {
this.wikipediaId = wikipediaId;
}
public String getGuid() {
return guid;
}
public void setGuid(String guid) {
this.guid = guid;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEthnicity() {
return ethnicity;
}
public void setEthnicity(String ethnicity) {
this.ethnicity = ethnicity;
}
public String getArticleText() {
return articleText;
}
public void setArticleText(String articleText) {
this.articleText = articleText;
}
public String getDob() {
return dob;
}
public void setDob(String dob) {
this.dob = dob;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getSiblings() {
return siblings;
}
public void setSiblings(String siblings) {
this.siblings = siblings;
}
public String getIntendedSearch() {
return intendedSearch;
}
public void setIntendedSearch(String intendedSearch) {
this.intendedSearch = intendedSearch;
}
}
Here is my CSV writer method
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import org.supercsv.io.CsvBeanWriter;
import org.supercsv.prefs.CsvPreference;
public class CSVUtils {
public static void writeCSVFromList(ArrayList<FreebasePeopleResults> people, boolean writeHeader) throws IOException{
//String[] header = new String []{"title","acronym","globalId","interfaceId","developer","description","publisher","genre","subGenre","platform","esrb","reviewScore","releaseDate","price","cheatArticleId"};
FileWriter file = new FileWriter("/brian/brian/Documents/people-freebase.csv", true);
// write the partial data
CsvBeanWriter writer = new CsvBeanWriter(file, CsvPreference.EXCEL_PREFERENCE);
for(FreebasePeopleResults person:people){
writer.write(person);
}
writer.close();
// show output
}
}
I keep getting output errors. Here is the error:
There is no content to write for line 2 context: Line: 2 Column: 0 Raw line:
null
Now, I know it is now totally null, so I am confused.
So it's been a while, and you've probably moved on from this, but...
The issue was actually that you weren't supplying the header to the write() method, i.e. it should be
writer.write(person, header);
Unfortunately the API is a little misleading in it's use of the var-args notation in the signature of the write() method, as it allows null to be passed in. The javadoc clearly states that you shouldn't do this, but there was no null-check in the implementation: hence the exception you were getting.
/**
* Write an object
*
* #param source
* at object (bean instance) whose values to extract
* #param nameMapping
* defines the fields of the class that must be written.
* null values are not allowed
* #since 1.0
*/
public void write(Object source, String... nameMapping) throws IOException,
SuperCSVReflectionException;
Super CSV 2.0.0-beta-1 is out now. It retains the var-args in the write() method, but fails fast if you provide a null, so you know exactly what's wrong when you get a NullPointerException with the following:
the nameMapping array can't be null as it's used to map from fields to
columns
It also includes many bug fixes and new features (including Maven support and a new Dozer extension for mapping nested properties and arrays/Collections).
I don't see where you create ArrayList<FreebasePeopleResults> people, but you might verify that it has more than one element. As an example of coding to the interface, consider using List<FreebasePeopleResults> people as the formal parameter.
Addendum: Have you been able to make this Code example: Write a file with a header work?
Example: Here's a simplified example. I think you just need to specify the nameMapping when you invoke write(). Those names determine what get methods to call via introspection.
Console output:
name,age
Alpha,1
Beta,2
Gamma,3
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import org.supercsv.io.CsvBeanWriter;
import org.supercsv.io.ICsvBeanWriter;
import org.supercsv.prefs.CsvPreference;
public class Main {
private static final List<Person> people = new ArrayList<Person>();
public static void main(String[] args) throws IOException {
people.add(new Person("Alpha", 1));
people.add(new Person("Beta", 2));
people.add(new Person("Gamma", 3));
ICsvBeanWriter writer = new CsvBeanWriter(
new PrintWriter(System.out), CsvPreference.STANDARD_PREFERENCE);
try {
final String[] nameMapping = new String[]{"name", "age"};
writer.writeHeader(nameMapping);
for (Person p : people) {
writer.write(p, nameMapping);
}
} finally {
writer.close();
}
}
}
public class Person {
String name;
Integer age;
public Person(String name, Integer age) {
this.name = name;
this.age = age;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
CellProcessor[] processors = new CellProcessor[] { new Optional(), new NotNull(),
new Optional(), new Optional(), new NotNull(), new Optional()};
CsvBeanWriter writer = new CsvBeanWriter(file, CsvPreference.EXCEL_PREFERENCE)
writer.write(data,properties,processors);