【发布时间】:2016-07-14 07:00:21
【问题描述】:
我试图用 CSV 加载嵌套的 POJO。对于某些错误,我无法使其正常工作。
请在下面找到我的代码。下面的类 Person 包含两个 POJO 字段地址和属性
public class Person
{
public String firstname;
public String lastname;
public PersonAttribute attribs;
public Address address;
//Getters and setters
}
PersonAttribute class
{
public int height;
public int weight;
//Getters and setters
}
地址类
public class Address
{
public String city;
public String zipCode;
public GeoLocation geoLocation;
//getter 和 setter }
地理位置
public class GeoLocation
{
private String latitude;
private String longitude;
//getter 和 setter }
现在我正在尝试读取 CSV 并填充 person 类。我无法让它工作。这是我的代码
public class ReadWithCsvDozerBeanReader
{
private static final String CSV = "firstname, lastname, height, weight, city,zipcode,latitude,longitude\n"
+ "bill,smith,180,200,ABC,123,48.8525525,2.3417763\n" + "james,smith,192,250,DEF,456,48.852129,2.3355093";
private static final int ATT_START_INDEX = 2;
private static final int ADDRESS_START_INDEX = 4;
private static final int GEO_LOCATION_START_INDEX = 6;
// custom preferences required because CSV contains spaces that aren't part
// of the data
private static final CsvPreference PREFS = new CsvPreference.Builder(
CsvPreference.STANDARD_PREFERENCE).surroundingSpacesNeedQuotes(true).build();
public static void main (String[] args) throws IOException
{
readWithCsvDozerBeanReader(new StringReader(CSV));
}
private static void readWithCsvDozerBeanReader (final Reader reader) throws IOException
{
ICsvDozerBeanReader beanReader = null;
try
{
beanReader = new CsvDozerBeanReader(reader, PREFS);
final String[] header = beanReader.getHeader(true);
// set up the field mapping, processors and hints dynamically
final String[] fieldMapping = new String[header.length];
final CellProcessor[] processors = new CellProcessor[header.length];
final Class<?>[] hintTypes = new Class<?>[header.length];
for (int i = 0; i < header.length; i++)
{
if (i < ATT_START_INDEX)
{
// normal mappings
fieldMapping[i] = header[i];
processors[i] = new NotNull();
hintTypes[i] = Person.class;
}
else if (i < ADDRESS_START_INDEX)
{
// attribute mappings
fieldMapping[i] = header[i];
processors[i] = new NotNull();
hintTypes[i] = PersonAttribute.class;
}
else if (i < GEO_LOCATION_START_INDEX)
{
// Address mappings
fieldMapping[i] = header[i];
hintTypes[i] = Address.class;
}
else
{
fieldMapping[i] = header[i];
hintTypes[i] = GeoLocation.class;
}
}
beanReader.configureBeanMapping(Person.class, fieldMapping, hintTypes);
Person person;
while ((person = beanReader.read(Person.class, processors)) != null)
{
System.out.println(String.format("lineNo=%s, rowNo=%s, person=%s", beanReader.getLineNumber(),
beanReader.getRowNumber(), person));
}
}
finally
{
if (beanReader != null)
{
beanReader.close();
}
}
}
}
我收到以下错误 线程“主”org.dozer.MappingException 中的异常:找不到类中字段(高度)的读取或写入方法
【问题讨论】: