目前我使用以下方法,但我不喜欢它:
JSONObject formJsonObj = new JSONObject();
formJsonObj.put("whatever", "whatever is inside");
ByteArrayOutputStream b = new ByteArrayOutputStream();
ObjectOutputStream o = new ObjectOutputStream(b);
o.writeObject(formJsonObj );
byte[] byteArray = b.toByteArray();
SerialBlob blob = new SerialBlob(byteArray);
有更好的方法吗?
最佳答案
您可能不喜欢您的方法的主要原因是 JSONObject 不可序列化并且 writeObject(formJsonObj ) 抛出异常。 Java 的 ObjectOutputStream 要求它序列化的对象实现 Serialized。
我建议使用 JSONObject 的 toString 方法,因为它将以最小化形式返回基于文本的 json 表示形式。一个简单的实现如下所示。
public static SerialBlob JSONToBlob(JSONObject object) throws SQLException {
String text = object.toString();
text = text == null ? "{}" : text;
return new SerialBlob(text.getBytes());
}
public static JSONObject blobToJSON(SerialBlob blob) throws SerialException, IOException, JSONException {
InputStream result = blob.getBinaryStream();
String jsonString = new String(toByteArray(result));
return new JSONObject(jsonString);
}
private static byte[] toByteArray(InputStream result) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
int i;
while(( i = result.read())== -1) {
out.write(i);
}
return out.toByteArray();
}
关于java - 将 org.json.JSONObject 转换为 javax.sql.rowset.serial.SerialBlob 的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35464533/