Scala Pickling似乎不适用于Point2D.Double

时间:2015-07-28 07:44:57

标签: json scala scala-pickling

我正在使用Scala程序,该程序使用Scala Pickling library序列化和反序列化包含MapString对象的Point2D.Double对象。 java.awt.geom包。

以下是相关逻辑:

contents +=
      new Button("Save Config") {
        reactions += {
          case ButtonClicked(_) => {
            var m: Map[String, Point2D.Double] = Map()
            nodeFields.foreach(x => {
              m += (x._1 -> new Point2D.Double(x._2._1.text.toDouble, x._2._2.text.toDouble))
            })
            val pkl = m.pickle
            fc.showSaveDialog(null)
            val outputFile = fc.selectedFile
            val writer = new PrintWriter(outputFile)
            writer.write(pkl.value)
            writer.close()
            Dialog.showMessage(null, "Success!")
          }
        }
      }

如果您需要查看更多内容,请here's the commit with the offending logic

目前,pkl.value的JSON格式字符串输出是一个有效的序列化Map[String, Point2D.Double],但Point2D.Double的值被删除了!

这是输出的片段:

{
  "$type": "scala.collection.mutable.Map[java.lang.String,java.awt.geom.Point2D.Double]",
  "elems": [
    {
    "$type": "scala.Tuple2[java.lang.String,java.awt.geom.Point2D.Double]",
    "_1": "BOTTOMLANE\r",
    "_2": {

    }
  },
    {
    "$type": "scala.Tuple2[java.lang.String,java.awt.geom.Point2D.Double]",
    "_1": "UPPERLANESECOND_0\r",
    "_2": {

    }
  },
    {
    "$type": "scala.Tuple2[java.lang.String,java.awt.geom.Point2D.Double]",
    "_1": "upperSecondTower_1",
    "_2": {

    }
  },
...
  ]
}

我该怎么做才能解决这个问题?

1 个答案:

答案 0 :(得分:4)

scala-pickling无法直接pickle / unpickle Point2D.Double,因为它没有公共字段(x和y值可通过getXgetY getter访问)。

Pickler的{​​{1}} / Unpickler可能是:

Point2D.Double

可以用作:

object Point2DPickler { 
  import scala.pickling._
  import scala.pickling.Defaults._
  import java.awt.geom.Point2D

  type DoublePoint = java.awt.geom.Point2D.Double
  implicit object Point2DDoublePickle extends Pickler[DoublePoint] with Unpickler[DoublePoint] {
    private val doubleUnpickler = implicitly[Unpickler[Double]]    

    override def tag = FastTypeTag[java.awt.geom.Point2D.Double]

    override def pickle(point: DoublePoint, builder: PBuilder) = {
      builder.beginEntry(point)
      builder.putField("x",
        b => b.hintTag(FastTypeTag.Double).beginEntry(point.getX).endEntry()
      )
      builder.putField("y",
        b => b.hintTag(FastTypeTag.Double).beginEntry(point.getY).endEntry()
      )
      builder.endEntry()
    }

    override def unpickle(tag: String, reader: PReader): DoublePoint = {
      val x = doubleUnpickler.unpickleEntry(reader.readField("x")).asInstanceOf[Double]
      val y = doubleUnpickler.unpickleEntry(reader.readField("y")).asInstanceOf[Double]
      new Point2D.Double(x, y)
    }
  }
}