Easy Scala Serialization?

被刻印的时光 ゝ 提交于 2019-12-04 19:29:48

问题


I'd like to serialization in Scala -- I've seen the likes of sjson and the @serializable annotation -- however, I have been unable to see how to get them to deal with 1 major hurdle -- Type Erasure and Generics in Libraries.

Take for example the Graph for Scala Library. I make heavy use of it in my code and would like to write several objects holding graphs to disk throughout my code for later analysis. However, many times the node and edge types are encapsulated in generic type arguments of another class I have. How can I properly serialize these classes without either modifying the library itself to deal with reflection or "dirtying" my code by importing a large number of Type Classes (serialization according to how an object is being viewed is wholly unsatisfying anyways...)?

Example,

class Container[N](val g: Graph[N,DiEdge]) {
   ...
}

// in another file
def myMethod[N](container: Container[N]): Unit = {
   <serialize container somehow here>
}

回答1:


To report on my findings, Java's XStream does a phenomenal job -- anything and everything, generics or otherwise, can be automatically serialized without any additional input. If you need a quick and no-work way to get serialization going, XStream is it!

However, it should be noted that the output XML will not be particularly concise without your own input. For example, every memory block used by Scala's HashMap will be recorded, even if most of them don't contain anything!




回答2:


If you are using Graphs for Scala and if JSON is your serialization format, you can directly use graph-json.

Here is the code and the doc.



来源:https://stackoverflow.com/questions/8061146/easy-scala-serialization

工具导航Map