我有一个想要更新的对象列表。基本上,我已经使用spring创建了我的对象,但对象的内容是空的。
我想使用Jackson解析器更新json文件中的对象列表。
json文件与对象兼容。这意味着我让映射器自动检测setter。
发生的情况是,映射器正在将对象加载到列表中,作为作为LinkedHashMap对象,而不是作为我的对象
这是我的json
[
{
"startDate":"01/06/2014 08:00",
"endDate":"01/06/2014 16:00",
"shiftType":"Regular",
"capacity":5
},
{
"startDate":"01/06/2014 16:00",
"endDate":"01/06/2014 23:00",
"shiftType":"Regular",
"capacity":5
},
{
"startDate":"01/06/2014 23:00",
"endDate":"02/06/2014 08:00",
"shiftType":"Regular",
"capacity":5
},
{
"startDate":"02/06/2014 08:00",
"endDate":"02/06/2014 16:00",
"shiftType":"Regular",
"capacity":5
},
]
这是我的目标
package il.co.shiftsgenerator.engine.model;
import java.text.ParseException;
import java.text.SimpleDateFormat;
public class ShiftConfiguration {
private int capacity;
private String shiftType;
private String startDate;
private String endDate;
private SimpleDateFormat dateFormat;
public int getCapacity() {
return capacity;
}
public String getStartDate() {
return startDate;
}
public void setStartDate(String startDate) throws ParseException {
dateFormat.parse(startDate);
this.startDate = startDate;
}
public String getEndDate() {
return endDate;
}
public void setEndDate(String endDate) throws ParseException {
dateFormat.parse(endDate);
this.endDate = endDate;
}
public void setCapacity(int capacity) {
this.capacity = capacity;
}
public String getShiftType() {
return shiftType;
}
public void setShiftType(String shiftType) {
this.shiftType = shiftType;
}
public SimpleDateFormat getDateFormat() {
return dateFormat;
}
public void setDateFormat(SimpleDateFormat dateFormat) {
this.dateFormat = dateFormat;
}
@Override
public String toString() {
return "ShiftConfiguration [capacity=" + capacity + ", shiftType="
+ shiftType + ", startDate=" + startDate + ", endDate="
+ endDate + "]";
}
}
这就是我试图加载数据的方式
ObjectMapper mapper = new ObjectMapper();
InputStream stream = fileLoaderHelper.getFileAsStream(SHIFT_CONFIG_LIST_JSON_FILE);
List<ShiftConfiguration> shiftBeans = new ArrayList<ShiftConfiguration>();
for (int i = 0; i < 21; i++) {
ShiftConfiguration shiftBean = context.getBean(ShiftConfiguration.class);
shiftBeans.add(shiftBean);
}
ObjectReader readerForUpdating = mapper.readerForUpdating(shiftBeans);
readerForUpdating.readValues(stream);
System.out.println(shiftBeans);
由于您的日期格式,它可能没有检测到正确的对象。我会试着明确地告诉杰克逊你约会时间的格式,也许这会解决问题。试试之类的东西
DateFormat df = new SimpleDateFormat("MM/dd/yyyy HH:mm");
mapper.setDateFormat(df);
在你的mapper.readerForUpdating调用之前,看看是否能做到。
这是因为您没有指定要使用的实际类型:您正在读取ShiftConfiguration
的List
,但没有指定类型。Jackson不知道期望的类型是什么:您只是给它一个要更新的对象,而且由于Java类型擦除,List
没有运行时泛型类型信息。
因此,您需要创建readerFor(new TypeRefererence<List<ShiftConfiguration>>() { })
,然后创建指示要更新List
的方法。
或者,您可能只想读取新列表,提供所需的类型信息,然后手动连接addAll(...)
。