Reading XML files from java - java

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;
}
}

Related

JAXB map to object insteadof string

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();
}
}
}

Error reading XML via JaxB

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 {
...
}

Stop converting < to &lt, > to &gt and & to & in spring controller response

I am trying to generate a small xml. This xml should have a CDATA in it. Now the problem is I managed to generate CDATA, but the xml that is generated have < and > and &
I am using spring-mvc. I am interested in getting the right xml with CDATA in it.
Sample xml is as follow :
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Customer>
<Active>1</Active>
<AlertMessage></AlertMessage>
<Currency>GBP</Currency>
<CustomerNumber>123</CustomerNumber>
<Forename>AD</Forename>
<balancetoallow>
<balance saving="10" spend="9990" type="2">
<value>\<![CDATA[$100 off on two purchase of jeans XYZ Brand.]]\></value>
</balance>
</balancetoallow>
<Surname>CD</Surname>
</Customer>
I have also overridden one of the converter as follow.
<mvc:annotation-driven>
<mvc:message-converters>
<bean
class="org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter">
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
P.S I am using spring rest controller for my web service.
Here is the model class :
public class Balance{
private String value;
private String type;
private String saving;
private String spend;
public String getValue() {
return value;
}
#XmlJavaTypeAdapter(AdapterCDATA.class)
public void setValue(String value) {
this.value = value;
}
public String getType() {
return type;
}
#XmlAttribute
public void setType(String type) {
this.type = type;
}
public String getSaving() {
return saving;
}
#XmlAttribute
public void setSaving(String saving) {
this.saving = saving;
}
public String getSpend() {
return spend;
}
#XmlAttribute
public void setSpend(String spend) {
this.spend = spend;
}
}
This class is again part of another class.
public class Balancetoallows {
private List<Balance> balancetoallow ;
public List<Balance> getBalancetoallow () {
return balancetoallow;
}
#XmlElement(name="balancetoallow ")
public void setBalancetoallow (List<Balance > balancetoallow ) {
this.balancetoallow= balancetoallow;
}
}
And this is part of this class.
The parent class.
#XmlRootElement(name = "Customer")
public class Customer {
private String surname ;
private String forename;
private BalanceToAllow balanceToAllow;
private final String active="1";
private final String currency = "GBP";
private final String alertMessage="";
public String getCustomerNumber() {
return customerNumber;
}
#XmlElement(name="CustomerNumber")
public void setCustomerNumber(String customerNumber) {
this.customerNumber = customerNumber;
}
#XmlElement(name="Active")
public String getActive() {
return active;
}
#XmlElement(name="Currency")
public String getCurrency() {
return currency;
}
public String getSurname() {
return surname;
}
#XmlElement(name="Surname")
public void setSurname(String surname) {
this.surname = surname;
}
public String getForename() {
return forename;
}
#XmlElement(name="Forename")
public void setForename(String forename) {
this.forename = forename;
}
#XmlElement(name="AlertMessage")
public String getAlertMessage() {
return alertMessage;
}
public BalanceToAllow getBalanceToAllow() {
return BalanceToAllow;
}
#XmlElement(name="balanceToAllow")
public void setFuturePromotions(BalanceToAllow balanceToAllow) {
this.balanceToAllow= balanceToAllow;
}
}
Thanks for reading.

Parsing XML data into string objects using JAXB

I have to parse a xml into string objects in JAXB. But how to creates objects for this xml
Country.xml
<?xml version="1.0" encoding="UTF-8"?>
<Country>
<name>India</name>
<capital>New Delhi</capital>
<population>120crores</population>
.
.
.
.
.
<states>
<state>
<name>Maharastra</name>
<pincode>xyzzzz</pincode>
<capital>Mumbai</capital>
<\state>
<state>
.
.
.
</state>
</states>
<\Country>
And to parse this xml I have created class to map the objects which creates the objects and print it in the console. But Don't know what I am doing wrong.
#XmlElementWrapper(name="Country")
public void setCountry(String Countryv) {
Country= Countryv;
}
#XmlElement (name = "name")
public void setname(String namev) {
name= namev;
}
#XmlElement (name = "capital")
public void setcapital(String capitalv) {
capital= capitalv;
}
#XmlElement (name = "population")
public void setpopulation(String populationv) {
population= populationv;
}
#XmlElementWrapper(name="states")
public void setType(String statesv) {
states = statesv;
}
#XmlElementWrapper(name="state")
public void setType(String statev) {
state = statev;
}
#XmlElement (name = "name")
public void setpopulation(String namev) {
name= namev;
}
#XmlElement (name = "pincode")
public void setpopulation(String pincodev) {
pincode= pincodev;
}
#XmlElement (name = "capital")
public void setpopulation(String capitalv) {
capital= capitalv;
}
when I run the program I m getting the
com.sun.xml.internal.bind.v2.runtime.IllegalAnnotationsException:
counts of IllegalAnnotationExceptions
How to add wrapper anotations to wrapping the elements under separate headers and headers inside other headers.
Try this class
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "", propOrder = {
"name",
"capital",
"population",
"states"
})
#XmlRootElement(name = "Country")
public class Country {
#XmlElement(required = true)
protected String name;
#XmlElement(required = true)
protected String capital;
#XmlElement(required = true)
protected String population;
#XmlElement(required = true)
protected Country.States states;
public String getName() {
return name;
}
public void setName(String value) {
this.name = value;
}
public String getCapital() {
return capital;
}
public void setCapital(String value) {
this.capital = value;
}
public String getPopulation() {
return population;
}
public void setPopulation(String value) {
this.population = value;
}
public Country.States getStates() {
return states;
}
public void setStates(Country.States value) {
this.states = value;
}
This worked for me
class Country {
#XmlElement
String name;
//...
#XmlElementWrapper(name="states")
List<State> state;
}
class State {
#XmlElement
String name;
//..
}

SUPER CSV write bean to CSV

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);

Categories