将org.json.JSONObject转换为javax.sql.rowset.serial.SerialBlob的最佳方式是什么?
目前我使用以下方法,但我不喜欢:将org.json.JSONObject转换为javax.sql.rowset.serial.SerialBlob的最佳方式是什么?,java,blob,jsonobject,Java,Blob,Jsonobject,目前我使用以下方法,但我不喜欢: JSONObject formJsonObj = new JSONObject(); formJsonObj.put("whatever", "whatever is inside"); ByteArrayOutputStream b = new ByteArrayOutputStream(); ObjectOutputStream o = new ObjectOutputStream(b); o.writeObject(formJsonObj ); byte
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(FormJSONObject)正在引发异常。Java的ObjectOutputStream要求它序列化的对象实现可序列化 我建议使用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();
}
您可以使用Json创建一个writer,并最终将writer中的字符串转换为byteArray
JSONObject myJson = new JSONObject();
myJson.put("key", "value");
Writer writer = new StringWriter();
Json.createWriter(writer).write(myjson);
SerialBlob blob = new SerialBlob(writer.toString().getBytes());
从SerialBlob到String
JsonReader reader=Json.createReader(serialBlob.getBinaryStream());
JsonObject myJson=reader.readObject();
一定有比将Java序列化应用于JSON对象更好的方法,但这行不通。write方法不接受org.json.JSONObject。