2016-02-17 87 views
0

目前我使用下面的方法,但我不喜歡它:將org.json.JSONObject轉換爲javax.sql.rowset.serial.SerialBlob的最佳方法是什麼?

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); 

有沒有更好的辦法?

+0

必須有優於方式將Java序列化應用於JSON對象 – wero

回答

2

你可能不喜歡你的方法的主要原因是JSONObject不是可序列化的,writeObject(formJsonObj)拋出異常。 Java的ObjectOutputStream要求它序列化的對象實現Serializable。

我會推薦使用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(); 
} 
0

您可以使用JSON來創建一個作家和finaly轉換器作家的字符串字節組

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(); 
相關問題