下面是把JSON轉成list後,轉成blob型態存入DB
ObjectMapper mapper = new ObjectMapper();//用Jackson處理JSON
Blob blob = null;
try {
SongResp dto = mapper.readValue(json, SongResp.class);
List list = dto.getSongs();
ByteArrayOutputStream bout = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bout);
oos.writeObject(list);
bout.close();
oos.close();
byte[] asBytes = bout.toByteArray();
blob = Hibernate.createBlob(asBytes);
} catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
以下是把DB中的該欄位取出成當時寫入的list
Listlist; Blob b = userDao.getUserData(id, dataType); try { if (b != null) { InputStream in = b.getBinaryStream(); ObjectInputStream ooi = new ObjectInputStream(in); in.close(); ooi.close(); list = (List)ooi.readObject(); return list; } } catch (SQLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); }
沒有留言:
張貼留言