当我执行此操作时,我得到了一个结果。但我想将结果转换成另一种形式。
public List<Data> getData() {
// TODO Auto-generated method stub
System.out.println("In getData dao************");
session=sessionFactory.openSession();
tx=session.beginTransaction();
List<Data> blist=session.createCriteria(>.class).list();
System.out.println("datalist dao************"+blist);
tx.commit();
session.close();
return blist;
}
Data.java
@Entity
@Table(name="tbl_genere")
public class Data implements Serializable{
private static final long serialVersionUID = 1L;
@Id
@Column(name="dataid")
private String DataId;
@Column(name="dataname")
private String DataName;
public String getDataId() {
return DataId;
}
public void setDataId(String dataId) {
DataId = dataId;
}
public String getDataName() {
return DataName;
}
public void setDataName(String dataName) {
DataName = dataName;
}
我得到[com.pack.web.model.Data@1233c96, com.pack.web.model.Data@5ec471]
的结果。但我需要将结果存储在json formate文件中。就像
{
"datalist":
{
"dataname1","dataname2","dataname3"
}
}
如何将其转换为此格式。
答案 0 :(得分:3)
尝试:
Gson gson = new Gson();
gson.toJson(datalist);
答案 1 :(得分:1)
使用jackson object mapper
即可:
ObjectMapper mapper = new ObjectMapper();
public String convertListArrayToJson(List<Object> objectList) throws JsonGenerationException, JsonMappingException, IOException {
// declaring string type final json array
String finalJsonArray = null;
// declaring the output stream for binding the data into the data
// variable
final OutputStream out = new ByteArrayOutputStream();
// writing the data to the json format using the mapper
mapper.writerWithDefaultPrettyPrinter().writeValue(out, objectList);
// converting the output to the byte data
final byte[] data = ((ByteArrayOutputStream) out).toByteArray();
// converting the byte data of json to the string and storing it to
// the final json array
finalJsonArray = new String(data);
return finalJsonArray;
}