我发布了我所做的,因为我没有得到结果。这里我有一个返回 ArrayList 的方法:
public ArrayList<Label> getLabels()
throws ClassNotFoundException, SQLException{
ArrayList<Label> labels = new ArrayList<>();
sq = "SELECT * from LABELS";
try {
Class.forName(typeDB);
c = DriverManager.getConnection(path);
stm = c.prepareStatement(sq);
ResultSet rs = stm.executeQuery();
while(rs.next()) {
Label label = new Label(rs.getString("type"), rs.getString("description"),rs.getString("product")+"-"+rs.getString("version"), rs.getString("cutter"));
labels.add(label);
}
} catch (SQLException e) {
System.out.println(e.getMessage());
} finally {
if (stm != null)
stm.close();
if (c != null)
c.close();
}
System.out.println("Label "+ labels.size());
return labels;
}
然后我想隐藏这个 ArrayList 来JSON
格式化。所以我在labelsToJSON(action.getLabels());
哪里执行:
public void labelsToJSON(ArrayList<Label> list){
ObjectMapper mapper = new ObjectMapper();
try{
mapper.writeValue(new File("C:\\temp\\labels.json"), list);
}catch(JsonGenerationException e){
e.printStackTrace();
}catch(JsonMappingException e){
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}
}
}
类Label
定义:
public class Label {
private String barcode;
private String labelCode;
private String productCode;
private String type;
//and many others..
public Label(){
}
//This is the costructor I use above in the method
public Label(String type, String description, String productCode, String cutter) {
this.type = type;
this.description = description;
this.productCode = productCode;
this.cutter = cutter;
}
//and then some other constructors (I post 2 for example)
public Label(String type, String description, String product, String version, String cutter) {
this.type = type;
this.description = description;
this.product = product;
this.version = version;
this.cutter = cutter;
}
public Label(String barcode, String product, String version, String dateProduction, String order , int quantity, String packetNumber, String type, String description, String cutter) {
this.barcode = barcode;
this.product = product;
this.version = version;
this.dateProduction = dateProduction;
this.order = order;
this.packetNumber = packetNumber;
this.quantity = quantity;
this.type = type;
this.description = description;
this.cutter = cutter;
}
//setters, getters etc
所以,我从带有参数的构造函数创建一个对象String type, String description, String productCode, String cutter
。但是labels.json
包含这些数据
[{
"barcode":null,
"labelCode":null,
"productCode":"111123123-1123", //<-
"type":"Container", //<-
"description":"this is a description", //<- all these I was expected.
"cutter":"1031", //<-
"date":null,
"time":null,
"dateProduction":null,
"order":null,
"product":null,
"version":null,
"packetNumber":null,
"quantity":0
}, //and so on
我不明白为什么json文件有这么多属性??我的对象应该只有 4 个 -->String type, String description, String productCode, String cutter