java - 将 org.json.JSONObject 转换为 javax.sql.rowset.serial.SerialBlob 的最佳方法是什么?

标签 java blob json

目前我使用以下方法,但我不喜欢它:

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/

相关文章:

java - 公开内部集合项时应该使用 Iterator 还是 Iterable?

java - Netty通过一个 channel 写入多条消息

java - 使用手动依赖注入(inject)构建多级对象树

javascript - 从 Blob 保存到本地文件

java - java中如何从使用数字作为标识符的JSON数组中获取值?

java - Android 振动已弃用。如何在 Android>= API 26 中使用 VibrationEffect?

cordova - 是否可以使用 phonegap 保存 blob?

javascript - 使用 Multer 将图像保存在 MongoDB 后端作为来自 Angular 的文件,它无法正常工作

javascript - 您如何缩小内部和数组的 promise 功能?

c# - 反序列化 JSON 颜色十六进制,不带引号