2016-12-14 108 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 
     } 
    } 
    }