2016-12-14 36 views
0

我在mongoDB中以二進制形式存儲了一個case case實例'Alert'。 我必須閱讀並鍵入現金'Alert'。scala - 將字節[]轉換爲大小寫類實例

我嘗試這樣

object MongoMain extends App { 
val uri = new MongoURI("url") 
    val mongoColl = MongoConnection(uri)("testdb")("alert") 
    val q = MongoDBObject("_id" -> ObjectId.massageToObjectId("5269c718ebb2e54b950a1cc1")) 
    // println(mongoColl.findOne(q)) 
    mongoColl.find(q).foreach { z ⇒ 
    z.get("message").getClass match { 
     case data: Class[Binary] ⇒ println(data.getSimpleName) 
     case _     ⇒ 
    } 
    } 
} 

該打印字節[],也就是說,它retriving消息字段作爲字節[]後,我必須將其轉換爲警報。我該怎麼做,需要幫助:

+3

您是如何將案例類存儲爲二進制的?你在那裏使用了什麼格式? Java對象序列化? – Thilo

回答

0

嘗試使用跟隨功能,希望它有幫助。

def deserializeAlert(data: Array[Byte]): Alert ={ 
    try { 
     val in = new ObjectInputStream(new ByteArrayInputStream(data)) 
     val alert = in.readObject.asInstanceOf[Alert] 
     in.close() 
     alert 
    } 
    catch { 
     case cnfe: ClassNotFoundException => { 
     cnfe.printStackTrace() 
     null 
     } 
     case ioe: IOException => { 
     ioe.printStackTrace() 
     null 
     } 
    } 
    }